in reply to Hashes: Deleting elements while iterating

This seemed to work for me on Perl 5.6 on Win32 and 5.8 on Linux
#!/usr/bin/perl -w use Data::Dumper; 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'; print Dumper \%index; # # DELETE all child nodes. # print "\nDelete children of $test\n"; foreach $key (sort keys %index){ if ($key =~ /$test.+/){ print "Deleting $key\n"; delete $index{$key}; } } print "\nFinal Hash:\n"; print Dumper \%index;
It outputted
$VAR1 = { 'node-cat-bat-bat-bat' => 5, 'node-bat-bat-cat' => 4, 'node-cat-cat-bat-bat' => 2, 'node-cat-cat-cat' => 4, 'node-cat' => 2, 'node-cat-cat-cat-cat' => 5, 'node-cat-cat' => 3, 'node' => 1 }; Delete children of node-cat-cat Deleting node-cat-cat-bat-bat Deleting node-cat-cat-cat Deleting node-cat-cat-cat-cat Final Hash: $VAR1 = { 'node-cat-bat-bat-bat' => 5, 'node-bat-bat-cat' => 4, 'node-cat' => 2, 'node-cat-cat' => 3, 'node' => 1 };
which is what you would expect.

Replies are listed 'Best First'.
Re: Re: Hashes: Deleting elements while iterating
by knexus (Hermit) on Sep 02, 2003 at 21:04 UTC
    <Grin>I think I was not clear enough or chose a less than obvious way to show things.</Grin>

    Yes, that approach worked for me as well. It's when I use

    foreach $key (%index){
    that I get the errors.

    If you look closely in the code I posted there are 3 loops above the delete operation, 2 of which are commented out. The ones commented out work, the other does not. I just change which one is UNcommented to test a particular way of doing it. I suppose this may seem unorthodox but it's just my way of trying to learn the differences/nuances of perl...

    So, what's the problem you might ask? ;-)
    Just seeking enlightenment as to why the one method gets errors (at least for me).

    Thanks for testing it out for me.