Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

How to sort array of hashes?

by gube (Parson)
on Dec 07, 2005 at 17:14 UTC ( [id://514907]=perlquestion: print w/replies, xml ) Need Help??

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/

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://514907]
Approved by Old_Gray_Bear
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (1)
As of 2024-04-25 00:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found