Sorting key,value pairs in a perl array data structure according to key(id) -
i trying sort key,value pairs present in array data structure in perl .however,i not resolve how sort when there multiple entries.
below code:
@users = ( {id => 1, name => "frank"}, {id => 10, name => "joe"}, {id => 5, name => "paul"} );
i want output sorted respect id in ascending order:
{id => 1, name => "frank"}, {id => 5, name => "paul"}, {id => 10, name => "joe"}
below effort:
use strict; use warnings; use 5.010; @users = ( {id => 1, name => "frank"}, {id => 10, name => "joe"}, {id => 5, name => "paul"} ); foreach $name (keys %users) { printf "%-8s %s\n",$users{id},$users{name}; }
any suggestions highly helpful.
you have conflicting specifications of data, need?
use strict; use warnings; use 5.010; @users = ( { id => 1, name => "frank" }, { id => 10, name => "joe" }, { id => 5, name => "paul" }, ); $item ( sort { $a->{id} <=> $b->{id} } @users ) { printf "%-8s %s\n", $item->{id}, $item->{name}; }
output
1 frank 5 paul 10 joe
Comments
Post a Comment