develooper Front page | perl.perl5.porters | Postings from June 2021

idea: everything-slices

Thread Next
From:
Ricardo Signes
Date:
June 20, 2021 01:54
Subject:
idea: everything-slices
Message ID:
586f4383-4c00-4398-a053-274e4ddf66b5@beta.fastmail.com
Porters,

I feel confident that this should be an RFC, but our process says "post to p5p before writing up an RFC," and "write something less format" sounds great.  So:

I would like to propose a new piece of syntax.  It's not my own original idea, it's come from a few places and individuals independently, but I'm the one who's ready to go to bat for it here.  It is the *everything slice*.

An everything slice is a slice that includes every element in an aggregate.  We can hash out syntax, but let's start by saying "it's a slice where the subscript is replaced by a literal asterisk."

So:

@array[*];  # equivalent to @array[ 0 .. $#array ];
%array[*];  # equivalent to %array[ 0 .. $#array ];

@hash{*};   # equivalent to @hash{ keys %hash };
%hash{*};   # equivalent to %hash{ keys %hash };

No, this is *not* the same as writing @array or %hash.  For one thing, when the \ operator is applied to a slice, it produces a list of references to individual elements, not a reference to the container.  Similarly, 

This provides an easy way to get all the keys and values of an array, which pairs nicely with multi-target for:
for my ($i, $v) (@array[*]) {
  ...
}

You can get a reverse lookup for arrays:
my %index_for = reverse %array[*];

You can assign a large list to an array without growing it:
@array = (1 .. 10);
@array[*] = @hundred_items; # @array remains 10 long

So:  if this is going to get shot down before it gets to an RFC, now's the time, but honestly I think you'll probably get to see me write an RFC for this within a week.

-- 
rjbs
Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About