in reply to Re: Re: Hashes: Deleting elements while iterating - deleting phantoms?
in thread Hashes: Deleting elements while iterating
if some kind soul would give an explanation of why the third antirice loop works, i could sleep easy. easier...
foreach my $key ( @{[%hash]} ) { print $key; delete $hash{$key}; }
What antirice has done here is to take a copy of the hash as a list. After this, interating over the copy means that every second delete attempts to delete a key that never existed in the hash and fails quietly while all the others succeed.
No doubt you're confused by the
bit.@{[%hash]}
Enclosing something in square brackets in Perl takes it in list context. It also generates an array reference to that. So %hash here is copied into an annoymous array. This is then deferenced by the @{}s because foreach expects a list, not a reference.
Does this help?
All the best,
jarich
|
|---|