Sort hashes

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on

Hi,

I have a need to sort a hash of hashes!  I know it already sounds
complicated, but its the only way I can think of holding the results of the
analysis of some data.

The hash has entries like:

\$ips = "02088887777"
\$ips = 1000
\$ips = 0

\$ips = "02077776666"
\$ips = 500
\$ips = 2

\$ips = "02077756666"
\$ips = 445
\$ips = 2

I need to sort it using the key "err_type"....is this easy?  I've never
understood sorting in Perl and so would appreciate any help you can give me.
"err_type" is always a number, if that's relevant!

- raj

Re: Sort hashes

Raj wrote:

> \$ips = "02088887777" \$ips = 1000
> \$ips = 0
>
> \$ips = "02077776666" \$ips = 500
> \$ips = 2
> ...
> I need to sort it using the key "err_type"....is this easy?  I've never
> understood sorting in Perl and so would appreciate any help you can give
> me. "err_type" is always a number, if that's relevant!

sub errtype { \$ips{ \$a } <=> \$ips{ \$b } }

for( sort errtype keys %ips ) {
print "\$_\n";
}

This gives the keys of your (level 0) hashes to sort. Sort uses a function
here, gives it \$a and \$b (the two values that get compared to tell which
is higher). These two vars (two keys of your level 0 hash) we use, well,
as keys for your level 0 hash, but we don't compare (maybe you lookup the
<=> operator) the keys (F6683) but the values of the err_type field in the
hashref saved as value to your level 0 hash.

g,phay

--
http://www.dunkelheit.at /
bellum omnium pater.

Re: Sort hashes

Raj wrote:
> I have a need to sort a hash of hashes!

perldoc -q "sort a hash"

> I've never understood sorting in Perl

perldoc -f sort

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