in reply to sorting an array from two sources

In the program below, I first read the main file into a hash of arrays with ID as the lookup key, and then I merge the total points in the sort file into the hash based on the ID's. A simple sort to get the sorted array of ID's, and then finally print the main data in sorted order.
use strict; use IO::File; # load main file my %main_data; my $f = new IO::File "mainfile.txt", "r" or die "Can't open main db: $ +!"; while(<$f>) { chomp; my @res = split /\t/; $main_data{$res[2]}{data} = \@res; # 3rd field is the ID number } undef $f; # load sort reference file my $f = new IO::File "sort.txt", "r" or die "Can't open sort.txt: $!"; while (<$f>) { chomp; my ($id, $total) = split /\t/; if (exists $main_data{$id}) { $main_data{$id}{total} = $total; # insert additional values } } # sort the main db in descending order my @sorted_id = sort { $main_data{$b}{total} <=> $main_data{$a}{total} } keys %main_data; # print sorted main db print "@{$main_data{$_}{data}}\n" foreach @sorted_id;
I have created the following simplified test data, note that as long as the 3rd field is the lookup id, it doesn't matter how many fields are in the main db.

mainfile.txt ------------ A B 12 C D 11 E F 10 sort.txt -------- 10 120.00 11 200.00
Note that I deliberately left out ID:12 to demonstrate the sort of undef values. The output result is:
C D 11 E F 10 A B 12
Note that ID:12 appears at the end, because 'undef' is less than defined values.

Replies are listed 'Best First'.
Re: Re: sorting an array from two sources
by Anonymous Monk on Oct 22, 2003 at 07:04 UTC
    Thanks for your input, Roger. I tested your solution and it works perfectly. I would still like to know where I'm falling down with my approach, though!
      Can you please post the full script? Seems like you have only posted a fraction of the code, and it doesn't even enclude the sort.