What I am seeing is a difference in behavior depending on how I iterate, when deleting hash elements. In the test code below, using the first foreach seems to work (the elements "appear" to be deleted) but I get errors:
Use of uninitalized value in pattern match (m//) at line 30.
Attempt free unreferenced scalar at line 27.
The other two iteration methods work fine without error. The main reason for this post is that I am still very new to perl (just a couple weeks) so I want to understand this behaviour (this may pass in time, when I just need to get it done... but for now ;-)
Note: I just commented out all but the one I wanted to test. Also, don't read too much into the names and comments in the code as it's superficial. :-)
Could this be caused by "buffering" (for lack of knowing a better term) by sort and each?
Thanks for any info/clarification and I gladly accept tips.
#!/usr/bin/perl -w use strict; my %index = ( 'node' => 1, 'node-cat' => 2, 'node-cat-cat' => 3, 'node-cat-cat-cat' => 4, 'node-bat-bat-cat' => 4, 'node-cat-cat-cat-cat' => 5, 'node-cat-bat-bat-bat' => 5, 'node-cat-cat-bat-bat' => 2, ); my $key; my $test='node-cat-cat'; foreach $key (sort keys %index) { print "$key: $index{$key}\n"; } # # DELETE all child nodes. # print "\nDelete children of $test :\n"; foreach $key (%index){ #foreach $key (sort keys %index){ #while ($key = each %index) { delete $index{$key} if ($key =~ /$test.+/); } print "\nFinal Hash:\n"; foreach $key (sort keys %index) { print "$key: $index{$key}\n"; }
In reply to Hashes: Deleting elements while iterating by knexus
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |