http://qs321.pair.com?node_id=11113731


in reply to RESOLVED - Autovivification: How Did I End Up With a Larger Number of Hash Keys Here?

Update: Yes, there's something going on here -- my example below has to do with a one-level hash, whereas the original is about a two-level hash. Nothing to see here. This is not the Perl code you're looking for. You can go about your business.

There must be something else going on here. Here's a simpler example that shows that I end up with fewer keys than I started with -- using just a one-dimensional hash. Code:

#!/usr/bin/perl use warnings; use strict; use Data::Dumper; { my %hash = ( 1 => 5, 3 => 12, 7 => 19, 9 => 44 ); print 'At ' . __LINE__ . ' there are ' . ( scalar keys %hash ) . " keys: "; print Dumper(\%hash); my %hash2 = ( 1 => 5, 9 => 22 ); print "This should delete one of the keys, using this hash ..\ +n"; print Dumper ( \%hash2 ); foreach my $key ( keys %hash2 ) { if ( exists $hash{ $key } ) { $hash{ $key } -= $hash2{ $key }; if ( $hash{ $key } <= 0 ) { delete $hash{ $key }; } } } print 'At ' . __LINE__ . ' there are ' . ( scalar keys %hash ) . " keys: "; print Dumper(\%hash); }
.. and the result:
tab@music4:~/Pianoforte/Development/Perlmonks/11113721 $ perl hashkeys +.pl At 11 there are 4 keys: $VAR1 = { '9' => 44, '1' => 5, '3' => 12, '7' => 19 }; This should delete one of the keys, using this hash .. $VAR1 = { '1' => 5, '9' => 22 }; At 33 there are 3 keys: $VAR1 = { '9' => 22, '3' => 12, '7' => 19 }; tab@music4:~/Pianoforte/Development/Perlmonks/11113721 $
I set the example up so that one of the keys would end up with zero (and get deleted), and another would be reduced, but not to zero. I started up with four keys, and finished with three.

Check your code -- I'm guessing you're missing something.

Alex / talexb / Toronto

Thanks PJ. We owe you so much. Groklaw -- RIP -- 2003 to 2013.