Connecting Tech Pros Worldwide Help | Site Map

How can you sort non-unique 'numeric keys' in a Perl hash

Tommo
Guest
 
Posts: n/a
#1: Jul 19 '05
Hello All,
I have a slight problem that goes like this. I have created
a Perl hash where the keys are made up of numeric values, I was then
sorting the 'keys' for this hash on their value (a<=>b etc), all was
well until I got 2 keys with the same value, I seem to loose one of
the hash entries. Is there a way around this problem ..

cheers, Mark ..
Gunnar Hjalmarsson
Guest
 
Posts: n/a
#2: Jul 19 '05

re: How can you sort non-unique 'numeric keys' in a Perl hash


Tommo wrote:[color=blue]
> I have created a Perl hash where the keys are made up of numeric
> values, I was then sorting the 'keys' for this hash on their value
> (a<=>b etc), all was well until I got 2 keys with the same value, I
> seem to loose one of the hash entries. Is there a way around this
> problem ..[/color]

Hash keys must be unique, so the way around it is to use some other
data structure.

--
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl

Gunnar Hjalmarsson
Guest
 
Posts: n/a
#3: Jul 19 '05

re: How can you sort non-unique 'numeric keys' in a Perl hash


Gunnar Hjalmarsson wrote:[color=blue]
> Hash keys must be unique, so the way around it is to use some other
> data structure.[/color]

A hash of arrays, maybe:

my %hash = (
1 => [ 130 ],
2 => [ 100, 125 ],
3 => [ 120 ],
);

for ( sort { $hash{$a}->[0] <=> $hash{$b}->[0] } keys %hash ) {
print "$_: ", ( join ', ', @{$hash{$_}} ), "\n";
}

--
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl

Closed Thread