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

Monks,

Hi, within the array i am having hashes i have to sort by name and store it in the array.. See the below example i want to sort by name in hashes and store it into array.

Thanks for your Code in Advance.

$VAR1 = { 'is_selected' => 1, 'name' => 'Me', 'user_id' => '1' }; $VAR2 = { 'is_selected' => 0, 'name' => 'Admin Admin', 'user_id' => '14' }; $VAR3 = { 'is_selected' => 0, 'name' => 'Proximate Shine', 'user_id' => '15' };

Replies are listed 'Best First'.
Re: How to sort array of hashes?
by swampyankee (Parson) on Dec 07, 2005 at 17:22 UTC
Re: How to sort array of hashes?
by serf (Chaplain) on Dec 07, 2005 at 17:36 UTC
    Or if you don't like using map:
    #!/usr/bin/perl use strict; use warnings; my @old_array = ( { 'is_selected' => 1, 'name' => 'Me', 'user_id' => '1' }, { 'is_selected' => 0, 'name' => 'Admin Admin', 'user_id' => '14' }, { 'is_selected' => 0, 'name' => 'Proximate Shine', 'user_id' => '15' } ); # # sort routine to sort by 'name' key in hash in array # sub by_name { ${$a}{'name'} cmp ${$b}{'name'} } my @new_array; for my $hash (sort by_name @old_array) { push (@new_array, $hash); } for my $hash (@new_array) { for my $key ( keys %{$hash} ) { print "$key => ${$hash}{$key}\n"; } print $/; }
Re: How to sort array of hashes?
by eff_i_g (Curate) on Dec 07, 2005 at 17:31 UTC
    Here's my try:
    #!/usr/bin/perl -w use strict; my %hash1 = ( is_selected => 1, name => 'Me', user_id => 1, ); my %hash2 = ( is_selected => 0, name => 'Admin Admin', user_id => 14, ); my %hash3 = ( is_selected => 0, name => 'Proximate Shine', user_id => 15, ); print join "\n" => my @sorted_names = sort map { $_->{name} } \(%hash1, %hash2, %hash3);
Re: How to sort array of hashes?
by holli (Abbot) on Dec 07, 2005 at 18:42 UTC
    If I get you right, it's as simple as this:
    my @unsorted = ( { 'is_selected' => 1, 'name' => 'Me', 'user_id' => '1' }, { 'is_selected' => 0, 'name' => 'Admin Admin', 'user_id' => '14' }, { 'is_selected' => 0, 'name' => 'Proximate Shine', 'user_id' => '15' } ); my @sorted = sort { $a->{name} cmp $b->{name} } @unsorted; print join "-", map { $_->{name} } @sorted; #Admin Admin-Me-Proximate +Shine


    holli, /regexed monk/