469,898 Members | 1,792 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,898 developers. It's quick & easy.

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

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 ..
Jul 19 '05 #1
2 5362
Tommo wrote:
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.

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

Jul 19 '05 #2
Gunnar Hjalmarsson wrote:
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";
}

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

Jul 19 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

7 posts views Thread by Christopher Jeris | last post: by
7 posts views Thread by Ireneusz SZCZESNIAK | last post: by
12 posts views Thread by Eva | last post: by
8 posts views Thread by Gary Owsiany | last post: by
48 posts views Thread by Alex Chudnovsky | last post: by
4 posts views Thread by Gaijinco | last post: by
5 posts views Thread by George2 | last post: by
1 post views Thread by Waqarahmed | last post: by
reply views Thread by Salome Sato | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.