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

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

Thread Previous | Thread Next
From:
Karen Etheridge
Date:
April 2, 2013 04:06
Subject:
Re: Perlfunc for each(), keys(), values() has been changed
Message ID:
20130329191033.GA13939@tequila.etheridge.ca

> > 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.
https://gist.github.com/karenetheridge/5272888

#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
efficient.)


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