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

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

Thread Previous | Thread Next
Karen Etheridge
April 2, 2013 04:06
Re: Perlfunc for each(), keys(), values() has been changed
Message ID:

> > I don't understand what you mean by "most recent key returned by each
> > or keys".  What is the most recent key returned by keys()?  Are you
> > trying to say you can delete during each() without changing the order
> > of subsequent keys/values returned by each()?
> Well it means that
> keys %hash; #reset each iterator
> while (my $key= each %hash) {
>   delete $hash{$key};
> }
> and
> foreach my $key (keys %hash) {
>   delete $hash{$key};
> }
> will never change the iteration order.

Not just that, but one can
1.  remove any key at all that has just been referenced by each(), even if it
is not the "last" key, and
2. remove keys in the order that they are returned by keys().

This code demonstrates these scenarios - in each case, the hash order never changes.

#1 certainly surprised me - but it provides for preservation of order by any
means of iterating through the hash (i.e. so long as one doesn't sort the
output of keys() or each(), order is preserved - which is presumably much more

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About