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.


In reply to Re: sorting an array from two sources by Roger
in thread sorting an array from two sources by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.