What Soko wants is that when he looks up a hash entry using a specific key, 5 for example, he gets multiple values. Perl does not do this. Instead, he gets the most recently defined value for key 5, "wu" in this instance. The others are gone.use English; use strict; my $key; my $value; print "HASH WITH DUPLICATES...\n"; my %mapdup = ( 1 => "one", 2 => "two", 5 => "five", # English 1 => "un", 2 => "deux", 5 => "cinq", # French 1 => "ein", 2 => "zwei", 5 => "funf", # German 1 => "bir", 2 => "iki", 5 => "bes", # Turkish 1 => "yi", 2 => "er", 5 => "wu", # Mandarin ); while (($key, $value) = each %mapdup) { print "($key, $value)\n" if defined $value; print "($key, <undef>)\n" if not defined $value; }
Allowing hashes with duplicate keys would be a great way to improve Perl. For now, we have to work around its limitations to acheive the same result. Here are some things that you could try. Adding to and removing values from these hash entries is left as an exercise for the reader. :-) You may want to look at the perllol and perldsc manpages.
use English; use strict; my $key; my $value; my $i; print "\nHASH OF LISTS\n"; my %maplist = ( 1 => [ ("one", "un", "ein") ], 2 => [ ("deux", "er", "two") ], 5 => [ ("five", "cinq", "bes", "funf") ], ); while (($key, $value) = each %maplist) { print "($key, @{$value})\n" if defined $value; print "($key, <undef>)\n" if not defined $value; } print "\nHASH OF ARRAYS\n"; my %maparray = ( 1 => ["one", "yi"], 2 => ["zwei", "iki", "two"], 5 => ["cinq", "five"], ); print "\n"; foreach my $elem (sort(keys %maparray)) { print "$elem: @{$maparray{$elem}}\n"; } print "\nHASH OF HASHES\n"; my %mapmap = ( 1 => { english => "one", french => "un", turkish => "bir" } +, 2 => { french => "duex", english => "two", mandarin => "er" } +, 5 => { german => "funf", french => "cinq", english => "five" } +, ); print "\n"; foreach my $elem ( sort {$a <=> $b} (keys %mapmap) ) { print "$elem: { "; foreach my $item (sort keys %{$mapmap{$elem}}) { print "$item=$mapmap{$elem}{$item} "; } print "}\n"; }
In reply to Re: 2 dimensional array sorting...
by Anonymous Monk
in thread 2 dimensional array sorting...
by Soko
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |