You're performing the split for each comparison of the elements in @data. This could add a significant amount of time to your file processing. Since the data does not change, it makes sense to do the split one time and cache the results.

The Schwartzian Transform is one solution. It combines the sorting on the 4th column that you need, with a more efficient one time split:

#!/usr/bin/perl -w use strict; open INPUT, "< $ARGV[0]" or die "Could not open file $ARGV[0]: $!"; my @sorted = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [ $_, (split /\s+/)[3] ] } <INPUT>; close INPUT; print "$_\n" for @sorted; __END__

Here's an explanation of how this works. Please remember you'll need to read the algorithm backwards, from the bottom to the top, to follow this explanation:

<INPUT> is turned into an array and processed through map. map build a temporary anonymous array, by placing the original line, held in $_, into position 0 of the anon. array. It then proceeds to split the line, and pull out the 4th column, which we then place into position 1.

Once every line in <INPUT> has been processed by map, they are all passed onto the sort function. Remember that as the elements come into sort, they are an anonymous array we built in the previous step. Now, we dereference these, and compared the date (in position 1), to each other.

Now, all of the lines are sorted in memory, they are passed into map a second time. map then proceeds to pull out every position 0 element, which were the original lines, and assigns these to @sorted.


In reply to (dkubb) Re: (2) Sorting lines in a file using the Schwartzian Transform by dkubb
in thread Sorting, arrays and other problems by TrinityInfinity

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.