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

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

Thread Previous | Thread Next
From:
demerphq
Date:
March 30, 2013 16:22
Subject:
Re: Perlfunc for each(), keys(), values() has been changed
Message ID:
CANgJU+Wkpoxht2477cGOho5_H0vPaPPrbvvTUiif1pt7xAKbnw@mail.gmail.com
On 30 March 2013 08:42, Eric Brine <ikegami@adaelis.com> wrote:
> On Sat, Mar 30, 2013 at 1:45 AM, demerphq <demerphq@gmail.com> wrote:
>>
>> On Friday, 29 March 2013, Eric Brine wrote:
>>>
>>> On Fri, Mar 29, 2013 at 10:39 AM, demerphq <demerphq@gmail.com> wrote:
>>>>
>>>> Well it means that
>>>>
>>>> foreach my $key (keys %hash) {
>>>>   delete $hash{$key};
>>>> }
>>>>
>>>> will never change the iteration order.
>>>
>>>
>>> So you can delete arbitrary keys without changing order?
>>
>>
>> I never said you could did I?
>
>
> Well, you said the following is doesn't change iteration order:
>
>
> foreach my $key (keys %hash) {
>   delete $hash{$key};
> }
>
> And the documentation is clear that the delete can be conditional, so that
> means the following doesn't change iteration order:
>
>
> foreach my $key (keys %hash) {
>   delete $hash{$key} if cond();
> }
>
> Since that deletes arbitrary keys, that means that deleting arbitrary keys
> doesn't change iteration order.

It's not an arbitrary key, its a key returned by traversing the items.

Saying it deletes arbitrary keys would mean this:

my $last;
foreach my $key (keys %hash) {
   delete $hash{$last} if defined $last;
   $last= $key;
}

would not change the order, which is not guaranteed

>>> On Fri, Mar 29, 2013 at 7:39 AM, demerphq <demerphq@gmail.com> wrote:
>>>>
>>>> Any insertion into the hash may change the order, as will any deletion
>>>
>>>
>>> So you can't delete arbitrary keys without changing order?
>>
>>
>> Have you been drinking? are you tryin to wind me up? I mean seriously, why
>> would you omit the text that immediately follows that which you are quoting?
>> The text that specifically states the one circumstance in which you can
>> delete an item from a hash and be guaranteed to not have the hash order
>> change...
>
>
> The text I did quote, and says you can delete arbitrary keys?

The full text is:

"Any insertion into the hash may change the order, as will any
deletion, with the exception
that the most recent key returned by C<each> or C<keys> may be deleted
without changing the order."

Which says that there is one circumstance you can delete a key which
is guaranteed not to change the iteration order.

Yves


-- 
perl -Mre=debug -e "/just|another|perl|hacker/"

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