|
||
|
Perl array sort routine.
This perl subroutine is listed here mainly for my own reference. I do not claim authorship and found this routine on the web quite sometime ago and have susequently lost the authors name. It is a superb sort routine for flat file databases. It is very quick and versatile, it will sort alphabetically or numericaly and in reverse. The database seperator can be defined on calling. Example Usage.... @sorted = fieldsort ':', ['2n', -1], @data; The @sorted array is returned with @data being the source. The delimeter is ":" and the array is to be sorted first by column 2 ascending numeric and then by column 1 descending alpha. It is that easy. sub fieldsort {
my ($sep, $cols);
if (ref $_[0]) {
$sep = '\\s+'
} else {
$sep = shift;
}
unless (ref($cols = shift) eq 'ARRAY') {
die "fieldsort columns must be in anon array";
}
my (@sortcode, @col);
my $col = 1;
for (@$cols) {
my ($a, $b) = /^-/ ? qw(b a) : qw(a b);
my $op = /n$/ ? '<=>' : 'cmp';
push @col, (/(\d+)/)[0] - 1;
push @sortcode, "\$${a}->[$col] $op \$${b}->[$col]";
$col++;
}
my $sortfunc = eval "sub { " . join (" or ", @sortcode) . " } ";
my $splitfunc = eval 'sub { (split /$sep/o, $_)[@col] } ';
return
map $_->[0],
sort { $sortfunc->() }
map [$_, $splitfunc->($_)],
@_;
}
#Example usage:
# as per above
#@sorted = fieldsort ':', ['2n', -1], @data;
# 2nd then 1st field, alpha, delimited by whitespace (\s+)
#@sorted = fieldsort [2, 1], @data;
# 1st descending numeric, then 3rd alpha, then 2nd numeric,
# delimited by '+'
#@sorted = fieldsort '+', ['-1n', 3, 2], @data;
|
||
|
|
||