develooper Front page | perl.perl5.porters | Postings from March 2013

Re: Perlfunc for each(), keys(), values() has been changed

Thread Previous | Thread Next
From:
Lukas Mai
Date:
March 29, 2013 17:40
Subject:
Re: Perlfunc for each(), keys(), values() has been changed
Message ID:
5155D1D8.6040008@gmail.com
On 29.03.2013 18:17, demerphq wrote:
> On 29 March 2013 18:10, Lukas Mai <plokinom@gmail.com> wrote:
>>
>> This bit ("or C<keys>") makes no sense: 'keys' always returns a complete
>> snapshot of the current keys. What does it mean for a key to be most
>> recently returned from 'keys'?
>>
>> Besides, code like 'for (keys %foo)' isn't iterating over a hash; it's
>> iterating over the list returned by 'keys', and in the loop body you can
>> modify %foo however you want.
>
> Actually id prefer to keep that language. Hypothetically it should be
> possible to optimize
>
> for my $key (keys %hash) {}
>
> so that it does not copy the full key list, and id like to keep the
> documentation at the level where it is clear what would have to remain
> true if we did so.

If this optimization makes it so I can't modify %hash in the foreach 
loop, then it would be a change in language semantics, not an 
"optimization". Besides, from the current documentation it is clear that 
perl can't do this.

If a future perl decides to break the usual rules of foreach/keys, it 
can be documented then. For now I see no point in telling users "hey, 
your foreach loops are potentially broken and you should change them 
just in case a future perl decides to do things differently".

Basically, as a Perl user I just want a simple way to iterate over a 
hash without having to think hard about it. Currently that way is 'for 
my $k (keys %hash)'. while/each is borderline unusable because you have 
to be 100% sure nothing in the loop body (including all nested sub 
calls) will use keys/values/each on the hash in question (this is why 
you don't put iterators in the iteratee itself, grr).
If a future perl changes the rules so that I can't simply modify the 
hash after calling keys on it, I'd have to change all my loops to 'for 
my $k (do { my @ks = keys %hash; @ks })' or something stupid like that. 
This feels too much like working around language bugs.

-- 
Lukas Mai <plokinom@gmail.com>

Thread Previous | 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