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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sorting Database File 1

Status
Not open for further replies.

jmds

Programmer
Feb 20, 2006
3
0
0
GB
Hi,

I have just started programming in perl cgi, I am trying to sort a text file that contains 2 fields:

category
categorydescription

I want to sort the file by categorydescription prior to listing the categories.

Could someone point me in the right direction of how to so this.

Many Thanks
John Messingham
 
How big is the file, and can we a sample of the file?

Paul
------------------------------------
Spend an hour a week on CPAN, helps cure all known programming ailments ;-)
 
Hi Paul,

Thanks for the reply.

The file will only contain a few records, the format is:

tlspro|The League System Pro|
tls|The League System|
tss|The Shop System|
tssne|The Shop System Network Edition|

I want to sort them by the second field, if possible. Once I crack this, I will be ok.

Many Thanks
John
 
is there really pipe "|" on the end of the lines like that?

One way I think you can understand is to use a hash:

Code:
my %sorted = ();
open(FILE,"<$yourfile") or die "$!";
while(<FILE>) {
   chomp;
   my ($first,$second) = split(/\|/);
   $sorted{$second} = $first;
}
for (sort {lc($a) cmp lc($b)} keys %sorted) {
   print "$_\n";
}

I used the lc() function (lower case) in the sort function because the default sort will sort capatalized characters before lower case characters, which might cause the sort to not be sorted how you want if the file is not exactly how you posted.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top