in reply to Re: Compare fields in a file
in thread Compare fields in a file

Nice! If I'm not mistaken, you can shorten it still:

use strict; use warnings; my $previous = ''; print grep { $_ } map { if ($previous ne $_->[1]) { $previous = $_->[1]; $_->[0]; } } sort { $a->[1] cmp $b->[1] or $b->[2] <=> $a->[2] } map { my ($date, $magnitude) = (split/,/)[3,4]; [ $_, join("", (split(/[-:. ]/,$date))[2,1,0,3,4,5]), $magnitude ] } <DATA>; __DATA__ 2550,531,66,10-12-2007 07:03:08.069,2 2549,529,62,10-12-2007 07:03:08.151,1 2550,531,66,10-12-2007 07:03:09.069,1 2549,529,62,10-12-2007 07:03:09.151,10 2549,529,62,10-12-2007 07:03:09.151,2 2549,529,62,10-12-2007 07:03:09.151,7 2549,529,62,10-12-2007 07:03:09.151,2 2549,529,62,10-12-2007 07:03:09.151,8 2549,529,62,10-12-2007 07:03:09.151,2 2549,529,62,10-02-2007 07:03:10.151,2 2549,529,62,10-12-2007 07:13:09.151,2 2549,529,62,10-12-2007 07:03:09.151,2 2549,529,62,10-12-2007 17:03:09.151,1

Gives me the same output as yours.

Update:Shortened a bit more and added strictures.

Update2: CountZero, thanks for pointing out the problem - it was subtle. I added a simple grep to fix it, which pretty much brings it back to your solution. Ah well, good stuff.

Replies are listed 'Best First'.
Re^3: Compare fields in a file
by CountZero (Bishop) on Feb 10, 2009 at 22:10 UTC
    Actually, there is a subtle difference: yours outputs an empty string for the elements which should be discarded. When printing this doesn't matter, but when saving it into an array, you will have lots of empty elements sprinkled through the array. Hence my use of grep which doesn't output anything if the value of its block is false.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James