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

T

Tommo

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 ..
 
G

Gunnar Hjalmarsson

Tommo said:
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 ..

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

Gunnar Hjalmarsson

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

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";
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top