Sort hashes

R

Raj

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{"F1234"}{"telephone"} = "02088887777"
$ips{"F1234"}{"charge"} = 1000
$ips{"F1234"}{"err_type"} = 0

$ips{"F6638"}{"telephone"} = "02077776666"
$ips{"F6638"}{"charge"} = 500
$ips{"F6638"}{"err_type"} = 2

$ips{"B7877"}{"telephone"} = "02077756666"
$ips{"B7877"}{"charge"} = 445
$ips{"B7877"}{"err_type"} = 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!

Thanks in advance,

- raj
 
P

phaylon

Raj said:
$ips{"F1234"}{"telephone"} = "02088887777" $ips{"F1234"}{"charge"} = 1000
$ips{"F1234"}{"err_type"} = 0

$ips{"F6638"}{"telephone"} = "02077776666" $ips{"F6638"}{"charge"} = 500
$ips{"F6638"}{"err_type"} = 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!

How about:

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

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
 

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

Forum statistics

Threads
474,167
Messages
2,570,913
Members
47,455
Latest member
Delilah Code

Latest Threads

Top