Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to use perl to sort string?

Status
Not open for further replies.

michael12

Programmer
Sep 26, 2002
25
0
0
US
I have a text file "test.txt":
----------
name age address
abc1 20 city1
abc2 15 city2
abc3 45 city3
abc4 19 city4
----------

How can I open this file, and print out the new one sorted by age? Thanks.
 
try this:
Code:
open (IN, "file.name") or die "Can't open file.name: $!";
open (OUT, ">outfile.txt") or die "Can't open outfile: $!";

my %hash;

while ($line = <IN>)
{
   if ($line =~ /^[a-z0-9]+\s([0-9]+)\s[a-z0-9]+/)
   {
      $hash{$1}{line} = $line;
   }
   else
   {
      print OUT, $line;
   }
}

foreach $key (sort keys %hash)
{
   print OUT, $hash{$key}{line};
}

close OUT;
close IN;
--Derek

&quot;Fear not the storm for this is where we grow strong.&quot;
 
oops, get rid of the commas after OUT in the print statements. --Derek

&quot;Fear not the storm for this is where we grow strong.&quot;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top