On Tue, 26 Jun 2001, Mark Bedish <[EMAIL PROTECTED]> wrote,
> I have a very simple tab delimited file containing text and numbers ,
> just the 2 columns and I would like to sort by ascending numeric. I have
> checked Learning Perl and Prog Perl but cannot get it to work - is that
> because you can only sort by key or am I using the wrong approach
> entirely?
>
> my @fields = qw/Text Time/;
> my %ch;
> foreach my $key (sort { $ch{1} cmp $ch{2} } keys %ch ) {
> print OUT "$key: $ch{$key} \n"; # show key and value
> }
One approach to have those lines in hash, another to have them
in array. This kind of data is usually stored in hash, but I
don't excatly your need.
About the sorting itself, perl provides $a and $b to represent
data source to be compared. In perlop manpage you'll see that
<=> is used for numeric data and cmp for string.
The file:
four 4
one 1
three 3
two 2
The prog:
my %ch;
open FILE, myfile or die "failed to open myfile: $!\n";
while (<FILE>) {
my($text, $num) = split /\t/;
$ch{$text} = $num;
}
close FILE;
I assume that "sort by ascending numeric" is sort ascending by
the number part of the line. We have keys of %ch as data source
and compare two of them in each turn. According to the structure
of %ch we know that $ch{KEY} will return numeric, so compare that
way.
foreach (sort { $ch{$a} <=> $ch{$b} } keys %ch) {
print "$_: $ch{$_}\n";
}
hth;
__END__
--
s::a::n->http(www.trabas.com)