Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a hash, in which i have extracted a number of keys and pushed into an array depending on a pattern match of values.

I now want to sort this array of keys in regards to different criteria within the original hash's values.

Is this even possible? If so, how would i go about doing something like this?

Thanks in advance for any help you can provide. =)

  • Comment on sorting arrays in respect to a different hash's values

Replies are listed 'Best First'.
Re: sorting arrays in respect to a different hash's values
by linuxer (Curate) on May 23, 2009 at 14:19 UTC

    Maybe this little example helps.

    #!/usr/bin/perl -l use strict; use warnings; my %hash = ( foo => 1, whatever => { rank => 11 }, you => { rank => 2 }, want => { rank => 7 }, ); my @arr = grep { $_ ne 'foo' } keys %hash; my @sorted = sort { $hash{$a}->{rank} <=> $hash{$b}->{rank} } @arr; print "@arr"; print "@sorted";

    Update:

    modified test data in code

    If your hash values are plain strings, than you just need to do something like:

    my @sorted = sort { $hash{$a} cmp $hash{$b} } @arr;

    See sort for more information about sort and the ways, how you can influence the sort.

    Also see Schwartzian Transform

    Update2: replaced <=> with cmp in second example; Thanks to AnomalousMonk and roboticus for pointing me on that.