Hi
Is there any way I could reproduce the following code in perl 5.8:
sort -u FILE | sort -t: -k1,1 -k2n
which sorts by unicity first, then by first key, then by second key in numeric format.
What I have now is
@sort_array=uniq sort @sort_array;
after the contents of my file have been loaded into this array. In clear, I lack the numeric sort on the second key.
Any thought?
Cheers
otheus
March 6, 2009, 10:21am
2
Not terribly easy.
First, for uniqueness:
my $prev;
@uniq_array=grep { if (defined $prev && $_ eq $prev) { 0; } else { $prev=$_; 1; } } @sort_array;
Second, build yourself a little sort function:
sub sort_special {
@a=split(":",$a);
@b=split(":",$b);
$a[0] cmp $b[0] || $a[1] <=> $b[1];
}
@sort_array=sort sort_special @uniq_array;
my %seen = ();
my @unique = grep { ! $seen{ $_ }++ } @array ;
perlfaq4 - perldoc.perl.org
A cached key sort should be more efficient but unless there is a lot of data to sort it might not make much difference. The code is rather cyrptic to the casual perl coder but it just strings together list functions to produce the list:
my %seen;
my @unique_sorted = map { "$_->[0]:$_->[1]" }
sort { $a->[0] cmp $b->[0] || $a->[0] <=> $b->[0] }
map { [split/:/] }
grep{! $seen{$_}++ } @unsorted;
Assumes all the data is in @unsorted and you don't need to do any other pre processing. Also, untested code.
otheus
March 7, 2009, 1:17am
5
Pretty cool. slight correction:
should be
sort { $a->[0] cmp $b->[0] || $a->[1] <=> $b->[1] }