On Feb 15, 2008 4:36 PM, <[EMAIL PROTECTED]> wrote:
> I'm trying to figure out how to do an Excel type sort in Perl but
> can't seem to find anything on specifically what I want to do. So here
> goes.
>
> Imagine 3 columns of numbers: A, B, C.
>
> I want to sort in descending order starting with Column A then Column
> B, and then Column C.
>
> Thing is I don't want the order of A to change when sorting B and i
> don't want the order of A or B to change when sorting C.
>
> I have no idea if the way to do this is with arrays or hashes.
snip
When sorting an array of arrays, $a and $b will contain array
references. Sorting an array of hashes works the same way (but $a and
$b will have hash references). Whether you should use an array of
arrays or an array of hashes depends on the things other than the
sort. In general, I try to use hashes to represent records as it
makes the code more self-documenting; however, some data lends itself
to arrays of arrays.
#!/usr/bin/perl
use strict;
use warnings;
my @aoa = (
["foo", 1, 3.4],
["foo", 2, 2],
["bar", 3, 10],
["bar", 3, 2],
["baz", 4, 0],
);
@aoa = sort {
$a->[0] cmp $b->[0] or
$a->[1] <=> $b->[1] or
$a->[2] <=> $b->[2]
} @aoa;
print "aoa:\n";
for my $row (@aoa) {
print "[EMAIL PROTECTED]";
}
my @aoh = (
{name => "foo", pos => 1, value => 3.4},
{name => "foo", pos => 2, value => 2},
{name => "bar", pos => 3, value => 10},
{name => "bar", pos => 3, value => 2},
{name => "baz", pos => 4, value => 0},
);
@aoh = sort {
$a->{name} cmp $b->{name} or
$a->{pos} <=> $b->{pos} or
$a->{value} <=> $b->{value}
} @aoh;
print "aoh:\n";
for my $row (@aoh) {
print "[EMAIL PROTECTED]<name pos value>}\n";
}
--
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/