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

Hi,

I've the following code:

my @data = ( { name => 'john', score => '70' }, { name => 'peter', score => '90' }, { name => 'dan', score => '50' }, ); foreach my $href (@data) { print "$href->{'name'}\t$href->{'score'}\n"; } # ouptput john 70 peter 90 dan 50
I'm thinking if there's a way to sort the array by 'score' to produce the output:

peter 90 john 70 dan 50
Is there a way to do it?

Thanks :)

2005-12-17 Retitled by GrandFather to fix spelling of references (to aid searching)
Original title: 'Sorting array of hash refereces'

Replies are listed 'Best First'.
Re: Sorting array of hash references
by bobf (Monsignor) on Dec 17, 2005 at 05:30 UTC
Re: Sorting array of hash references
by davido (Cardinal) on Dec 17, 2005 at 05:25 UTC

    Like this:

    my @sorted = sort { $a->{score} <=> $b->{score} or $a->{name} cmp $b->{name} } @unsorted;

    I employed logical short circuiting to allow the comparison routine to compare names if two equal scores are encountered.


    Dave

Re: Sorting array of hash references
by l.frankline (Hermit) on Dec 17, 2005 at 07:56 UTC
    my @data = ( { name => 'john', score => '70' }, { name => 'peter', score => '90' }, { name => 'dan', score => '50' }, ); my @new = sort { $a->{score} <=> $b->{score} } @data; print "$_->{'name'}\t$_->{'score'}\n" for (@new);

    regards,
    Franklin

    Don't put off till tomorrow, what you can do today.

Re: Sorting array of hash references
by Anonymous Monk on Dec 17, 2005 at 05:55 UTC
    Wonderful!

    I didn't know 'sort' can be used that way.

    Thank you so much :)