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

I'd like to sort on the "Name" field after the following select statement. I'm unsure how I should be manipulating the dereferenced data structure to enable a sort on "Name".

Any ideas what I should be doing?

Wylie
# create statement handle my $sth = $dbh->prepare(" SELECT ArchiveID,ArchiveName AS Name, ArchiveBrowseLocation AS Locat +ion FROM tblArchive WHERE ArchiveCategory LIKE '%$searchterm%' ORDER BY '$searchorder'"); #execute SQL search $sth->execute(); #create a reference to the search results $array_ref = $sth->fetchall_arrayref(); #Dereference the data structure returned by the #preceding line. #For each row in the returned array reference foreach my $row(@$array_ref) { my ( $ArchiveID, $Name, $Location ) = @$row; } #Sort statement in here. Something like the following? #@$row = sort { $name1 cmp $name2 } @$row; #output to another script to layout the HTML to follow
  • Comment on How do I sort on one of the fields in a dereferenced array reference?
  • Download Code

Replies are listed 'Best First'.
Re: How do I sort on one of the fields in a dereferenced array reference?
by Fletch (Bishop) on Apr 16, 2002 at 04:05 UTC

    perldoc -q 'how do I sort'

Re: How do I sort on one of the fields in a dereferenced array reference?
by particle (Vicar) on Apr 15, 2002 at 13:59 UTC
    if $row is a reference to an array, then $row->[$i] (where $i is the index) will access a particular list item. for more info, see perlref and perlreftut. also, see perldsc for info on complex data structures.

    also, sort won't work inside your for loop, as each row only has one name field. you have to sort all rows, as in my @new_array = sort { @{ $a }->[1] cmp @{ $b }->[1] } @{ $array_ref }; or something close to that.

    in this example, i don't see why you're not sorting this data in the database.