Gavin Laking wrote:
> 
> One of my scripts uses a home-brewed flatfile database to store
> information, and I've run up against a problem when I wish to sort
> columns of data.
> 
> An example of the database file:
> (items,fruit,date)
> 
> 16,apples,20021118-1725
> 22,bananas,20021118-1648
> 4,grapes,20021118-1921
> 
> To open and place the items into an array, I do this (formatted so that
> some mail client doesn't make it *really* unreadable :-P ) :
> 
> open ('FILE',"$databaseFile") || die;
> @dbfile = <FILE>;
> for ($a = 0; $a < @dbfile; $a++) {(
>         $items[$a],
>         $fruit[$a],
>         $date[$a],
>         $chop)=split(/,/,$dbfile[$a]);}
> 
> With a little pretty printing can show us the database in 3D. I'm not
> going to include the code for pretty printing here as it is unimportant,
> but the output I think is:
> 
> [0]16,[0]apples,[0]20021118-1725
> [1]22,[1]bananas,[1]20021118-1648
> [2]4,[2]grapes,[2]20021118-1921
> 
> Now my problem is that I can sort the database by 'items', both
> ascending and descending order:
> 
> (ascending)
> @dboutfile = sort {($a =~ /(\d+)/)[0] <=> ($b =~ /(\d+)/)[0]} @dbfile;
> 
> (descending)
> @dboutfile = sort {($b =~ /(\d+)/)[0] <=> ($a =~ /(\d+)/)[0]} @dbfile;
> 
> But I can't seem to sort the database by any of the other fields. I've
> tried incrementing the '0's and changing '\d+' to '\w+' but I can't get
> it into reverse alphabetical or chronological order or any other sort
> type other than ascending or descending 'items' order.
> 
> Does anybody know what I'm waffling about, and can solve this problem,
> or am I really blessed with programmers illiteracy? Thanks all,


You can make it a bit simpler if you use an array of arrays.

open( FILE, $databaseFile ) || die "Cannot open $databaseFile: $!";
my @dbfile;
while ( <FILE> ) {
    chomp;
    push @dbfile, [ split /,/ ];
    }

# Sort by item (ascending)
my @dboutfile = sort { $a->[0] <=> $b->[0] } @dbfile;

# Sort by fruit (descending)
my @dboutfile = sort { $b->[1] cmp $a->[1] } @dbfile;

# Sort by date (descending) then by item (ascending) then by fruit
(ascending)

my @dboutfile = sort { $b->[2] cmp $a->[2] or
                       $a->[0] <=> $b->[0] or
                       $a->[1] cmp $b->[1]   } @dbfile;



John
-- 
use Perl;
program
fulfillment

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to