Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sorting Arrays

Status
Not open for further replies.

rawkin

Programmer
Sep 23, 2003
11
AU
Hi,

I'm using an array of hashes to hold some data - a simplified example as follows;

my @values;

$values[0]{'name'} = "Bob";
$values[0]{'age'} = 41;

$values[1]{'name'} = "Fred";
$values[1]{'age'} = 25;

...

$values[25]{'name'} = "Joe";
$values[25]{'age'} = 38;

How can I go about sorting the array so that the elements are ordered by 'age'?


thanks,

Pete
 
If only I'd held out & kept searching for another 10-15mins ;-)

It all seems so easy after seeing the solution;

@values = sort {$a->{'age'} <=> $b->{'age'}} @values;


Pete
 
Here is some quick code that I hope helps
Code:
@values = (
   { name => 'Bob',  age => 41 },
   { name => 'Fred', age => 25 },
   { name => 'Joe',  age => 38 }
);  

for $rec ( sort { $a->{age} <=> $b->{age} } @values ) {
  print &quot;$rec->{name} is $rec->{age}.\n&quot;;
}
This will sort the ages in ascending order. To sort in descending order just flip the values in the comparison like:
Code:
sort { $b->{age} <=> $a->{age} } @values
Hope that helps.
 
Your speediest bet is probably something like this:
Code:
my $i = 0;
my @sorted =
	map { $values->[substr($_,1)]}
	sort
	map { pack('C',$_->{age}).$i++}
	@values;
We've got a good sort discussion going over at devshed right now:
----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top