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

Lets say I have the following array and hash reference:
my @id = ('001', '010', '014', '060', '071-1'); my $lid = {}; $lid->{'001'} = "United States"; $lid->{'010'} = "Mexico"; $lid->{'014'} = "Canada"; $lid->{'060'} = "Germany"; $lid->{'071-1'} = "Italy";
What would be the best/simplest way to sort the array according to the value stored in the hash reference?

For example, the sorted array (alphabetically) would be in this order:
014 060 071-1 010 001

Replies are listed 'Best First'.
Re: How do I sort an array by hash value?
by moritz (Cardinal) on Aug 17, 2009 at 20:39 UTC
    @id = sort { $lid->{$a} cmp $lid->{$b} } @id
    Perl 6 projects - links to (nearly) everything that is Perl 6.
      Wow that worked great. Thanks.
      Now what if the array is:
      my @id = ('001=0,2', '010=3', '014=0,0', '060=4', '071-1=3');
      And I want to sort the same way but ignoring the '=' sign and anything after.
Re: How do I sort an array by hash value?
by Tanktalus (Canon) on Aug 18, 2009 at 04:23 UTC
    use Sort::Key qw(keysort_inplace); keysort_inplace { $lid->{$_} } @id;
    As for your second question:
    keysort_inplace { /^([^=]*)/; $lid->{$1} } @id;
    I've taken a liking to the Sort::Key interface :-) Note that if your values that you're sorting by actually are numbers, you can put an "n" in front (nkeysort_inplace), or if they're integers (and fit into the native signed int's) use "i", or if they're unsigned integers (and, again, fit into the native unsigned int's) use "u" in front. If you want to put it into another array instead of replacing the existing @id, just remove _inplace, and assign: @sorted_ids = keysort { ... } @ids. Really nifty stuff :-)