coldfingertips has asked for the wisdom of the Perl Monks concerning the following question:
What I'm trying to do is after the delete occurs, rebuild the hash again so there aren't any number gaps with the keys.
If you run the code below, the results will be:
I don't know what's happened, but I should only have 0-3 left in my hash since I deleted {2} and for some reason it prints FOUR twice.C:\Documents and Settings\my\Desktop>perl test.pl 0 ==== zero 1 ==== one 2 ==== three 3 ==== four 4 ==== four
Where did I go wrong?
#!/usr/bin/perl use warnings; use strict; my %hash = ( "0" => "zero", "1" => "one", "2" => "two", "3" => "three", "4" => "four" ); delete $hash{2}; my $num = "-1"; foreach (sort keys %hash) { $num++; my $value = $hash{$_}; $hash{$num} = $value; } foreach (sort keys %hash) { print "$_ ==== $hash{$_}\n"; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: rebuilding hashes
by Zaxo (Archbishop) on Feb 02, 2004 at 19:06 UTC | |
by coldfingertips (Pilgrim) on Feb 02, 2004 at 20:14 UTC | |
by duff (Parson) on Feb 02, 2004 at 20:36 UTC | |
by stvn (Monsignor) on Feb 02, 2004 at 21:02 UTC | |
by ysth (Canon) on Feb 02, 2004 at 21:36 UTC | |
|
Re: rebuilding hashes
by Limbic~Region (Chancellor) on Feb 02, 2004 at 19:04 UTC | |
|
Re: rebuilding hashes
by diotalevi (Canon) on Feb 02, 2004 at 19:05 UTC | |
|
Re: rebuilding hashes
by Abigail-II (Bishop) on Feb 02, 2004 at 19:03 UTC | |
|