Reverse Sorting in Perl

They have: 4 posts

Joined: Mar 2000

I am trying to reverse sort a flat-file, pipe delimited database so that I can display records in descending order. I need to sort the records by ID number and the ID number is the first field in my database file. (Ex. ID|Title|Image|Message) Any help would be greatly appreciated. I will probably have to use the reverse sort function in Perl, but I'm not sure how do it so that it will sort one database file based on a numeric field value.

Thanks,
Dave

They have: 568 posts

Joined: Nov 1999

I believe I have something for you.

code:

for my $x (0..scalar(@array)) {
   $id[$x] .= "|" . $rest[$x];
}

@sorted =
map { join "|", @$_ }
sort { $b->[1] <=> $a->[1] }
map { [ split /\|/ ] }
@array; 
[/code]

you may have to change the code around a little but you get the ideas.... 

They have: 850 posts

Joined: Jul 1999

So if it had

1|Title|Image|Message\n
2|Title|Image|Message\n

you would just want it to be
2|Title|Image|Message\n
1|Title|Image|Message\n
?

That doesn't seem hard, just try:

code:

open(IN,"<IN.txt");
@arr = <IN>;
close(IN)

@arr = sort @arr;
@arr = reverse @arr;

open(IN,">IN.txt");
print IN @arr;
close(IN);
[/code]


------------------
Termites eat through wood two times faster when listening to rock music.

[This message has been edited by robp (edited 14 March 2000).] 

They have: 568 posts

Joined: Nov 1999

Robp That would work fine but what if he's going to have more than 9 entries into the database?

Remember sort will work but it will only sort by the first number of every line.

So if he had 1 15 25 12 it would sort it as
1 15 12 25... and thats not good

They have: 568 posts

Joined: Nov 1999

Robp Would you be willing to help me out with my web site? i.e. make scripts and tutorials. I've seen a ton of your postings around the forum and you seem to be as knowledgable (if not more) about perl as me.

Want to help out?
email me [email protected] (nice email isn't it

They have: 4 posts

Joined: Mar 2000

Do you know how I can modify the code to handle the sorting of numeric values above 9?

They have: 850 posts

Joined: Jul 1999

@arr = sort {$b <=> $a} @arr;

------------------
Termites eat through wood two times faster when listening to rock music.

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.