in reply to Hashes: Deleting elements while iterating
The answer the OP was seeking has been well-demonstrated already. However, in attempting to come up with examples to show him why this behaves the way it does, I came across some very interesting behavior.
#!/usr/bin/perl -lw my %hash = qw(a b c d d c b a); foreach my $key (%hash) { print $key; delete $hash{$key}; } # output: # c # # a # Segmentation fault (core dumped) foreach my $key (%hash) { print $key; delete $hash{"$key"}; } # same output with seg fault foreach my $key ( @{[%hash]} ) { print $key; delete $hash{$key}; } # output: # c # d # a # b # b # a # d # c
I've tried it in both 5.6.1 and 5.8.0. From my understanding of hashes, this ought to work since according to perldoc -f delete the delete should just return undef if the hash element doesn't exist.
antirice
The first rule of Perl club is - use Perl
The ith rule of Perl club is - follow rule i - 1 for i > 1
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Hashes: Deleting elements while iterating - deleting phantoms?
by wufnik (Friar) on Sep 02, 2003 at 23:49 UTC | |
by jarich (Curate) on Sep 04, 2003 at 03:55 UTC | |
by Not_a_Number (Prior) on Sep 03, 2003 at 19:18 UTC |