in reply to I got it!
in thread Sorting, arrays and other problems
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.
|
|---|