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

I have the following code:
my @AoH = ( { Lead => "fred", Wife => "wilma", Son => "bambam", }, { Lead => "george", Wife => "jane", Son => "elroy", }, { Lead => "homer", Wife => "marge", Son => "bart", }); for my $i ( 0 .. $#AoH ) { print "$i is { "; for my $role ( keys %{ $AoH[$i] } ) { print "$role=$AoH[$i]{$role} "; } print "}\n"; }

This gives the following output:

0 is { Son=bambam Lead=fred Wife=wilma} 1 is { Son=elroy Lead=george Wife=jane } 2 is { Son=bart Lead=homer Wife=marge }
I want to create another array of hashes that sorts the original array of hashes based on the values of the "Son" field, so the output becomes:
Original AoH: 0 is { Son=bambam Lead=fred Wife=wilma} 1 is { Son=elroy Lead=george Wife=jane } 2 is { Son=bart Lead=homer Wife=marge } New AoH: 0 is { Son=bambam Lead=fred Wife=wilma} 1 is { Son=bart Lead=homer Wife=marge } 2 is { Son=elroy Lead=george Wife=jane }
How do I do this?

Replies are listed 'Best First'.
Re: How to sort an array of hashes based on one of the values in the hash?
by tangent (Parson) on Mar 08, 2013 at 15:29 UTC
    With real world data I would use:
    @AoH = sort { lc($a->{'Son'}) cmp lc($b->{'Son'}) } @AoH;
Re: How to sort an array of hashes based on one of the values in the hash?
by blue_cowdawg (Monsignor) on Mar 08, 2013 at 15:25 UTC

    ############################################## # Wrong! (thanks tobylink) #@AoH = sort { $a->{Son} <=> $b->{Son} } @AoH; # Correct. @AoH = sort { $a->{Son} cmp $b->{Son} } @AoH;


    Peter L. Berghold -- Unix Professional
    Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg

      Yes, but you want cmp not <=>.

      cmp is for ASCIIbetical sorting; <=> is for numeric sorting. (And Unicode::Collate is for proper, decent alphabetical sorting.)

      package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name
            Yes, but you want cmp not <=>.

        Dammit! My fingertips did it again! I thought one thing and typed another!


        Peter L. Berghold -- Unix Professional
        Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg