Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: sorting hashes

by AnomalousMonk (Archbishop)
on Mar 24, 2009 at 19:45 UTC ( [id://752947]=note: print w/replies, xml ) Need Help??


in reply to sorting hashes

I am not sure I understand what you require, but if it is "How might I sort the keys or values of a hash by the index in the  @cols array of the value of the hash element", then it is necessary to first make a mapping of the elements of the  @cols array to their indices: another hash.

Once you have the element-to-index mapping of the array, it is straightforward to sort the keys or values of the original hash by these indices.

>perl -wMstrict -le "my @cols = qw(bar wobble mosh hop); my %hash = ( wibble => $cols[1], foo => $cols[0], hip => $cols[3], mish => $cols[2], ); my %i_map = map { $cols[$_] => $_ } 0 .. $#cols; print join ' ', qq{keys sorted by \@cols index of value: \n}, sort { $i_map{ $hash{$a} } <=> $i_map{ $hash{$b} } } keys %hash ; print join ' ', qq{values sorted by \@cols index of value: \n}, sort { $i_map{$a} <=> $i_map{$b} } values %hash ; " keys sorted by @cols index of value: foo wibble mish hip values sorted by @cols index of value: bar wobble mosh hop
The preceding assumes that every value of the hash is an element of the array; it would be wise to validate this assumption.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://752947]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (2)
As of 2024-04-20 06:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found