Home: Perl Programming Help: Beginner:
Sorting an array !



seriousfun
Novice

Jun 10, 2000, 2:45 PM


Views: 1201
Sorting an array !

I have a script which produces its search results in an array holding the various fields in format like fieldone|fieldtwo|fieldthree|etc...

My question is how do I sort the array into numerical order of field one at the same time keeping all other fields in the array attached to field one ( in effect all field sorted with field one)

All help is warmly appreciated.


dws
Deleted

Jun 11, 2000, 10:06 AM


Views: 1201
Re: Sorting an array !

Use a "Schwartzian Transform". The idea is to turn each datum into an anonymous array that contains the initial datum plus some aspect of it (in this case, the leading digit), then sort the anonymous arrays based on the aspect, then turn the anonymous arrays back into the original datum.

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

@data = ("1|foo", "10|baz", "5|bar");

@sorted = map { $_->[0] }
sort { $a->[1] <=> $b->[1] }
map { [ $_, (split /\|/, $_)[0] ] }
@data;

print join "\n", @sorted;</pre><HR></BLOCKQUOTE>




dws
Deleted

Jun 11, 2000, 10:19 AM


Views: 1201
Re: Sorting an array !

On second thought, the Schwartzian Transform isn't a beginner move. You might be better off with something like this, which takes the simple approach of building a hash keyed by the id from each record, then sorting the keys.
<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

data = ("1|foo", "10|baz", "5|bar");
%by_id = ();

foreach ( @data ) {
/^(\d+)\|/;
$by_id{$1} = $_;
}

foreach ( sort { $a <=> $b } keys %by_id ) {
print $by_id{$_}, "\n";
}</pre><HR></BLOCKQUOTE>