On Tue, Jun 07, 2005 at 10:40:43PM -0400, Jeremy Kister wrote: > I'm stumped on how to sort an array based on a hash refrences's key in > each element of my array. > > this is dumbed down code of what I have: > my @array; > while(my $row = $sth->fetchrow_arrayref){ > my %hash = (id => $row->[0], name => $row->[1]); > push(@array, \%hash); > } > > after the while loop, I'm trying to build a new version of @array, > sorted by the 'name' key. >
Sort as its first argument can take a code block with the two special variables $a and $b passed to this block for each iteration of the sort algorithm. The return values must must be one of -1 0 or 1, which have the same meaning as in the cmp and <=> comapriosn operators. In other words in you case you want to do: @array = sort { $a->{name} cmp $b->{name} } @array; I hope the dereferencing above is pretty self explanatory. Try perldoc -f sort for more info - there are some pretty nifty examples in there. Peter -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>