Click to See Complete Forum and Search --> : sorting


paperbox005
09-23-2004, 10:48 AM
i am reading from a file that contains a name and a number something like
name1 num1
name2 num2
name3 num3

what is the best way to sort these names by their number values?
i've tried placing them in two arrays and sorting the number array and then finding the corresponding name but thats not going to plan..

can anyone suggest another way?

also can i use perl to write to a file? will i need to have some cgi script of some sort, or can perl do it?

thanks

Charles
09-23-2004, 02:04 PM
#!c:/perl/bin/perl.exe -w

use strict;

my %foo;
while (<DATA>) {
my ($key, $value) = split /\s/;
$foo{$key} = $value;
}

print "by name:\n\n";
foreach (sort keys %foo) {print "\t$_ => $foo{$_}\n"};

print "by number:\n\n";
foreach (sort {$foo{$a} <=> $foo{$b}} keys %foo) {print "\t$_ => $foo{$_}\n"};


__DATA__
fee 3
fie 1
foe 4
fum 2