PDA

View Full Version : Flat-File DB sorting. (perl)



skirrow
May 27th, 2001, 13:27
Hi,
Ok, I have a flat file database which looks something like this:


$name|$rdate

Actually, it looks nothing like that but it gives you the idea.
The file has quite a few records in it, one per line.

What I want to do is display the 5 most recent additions.
Ordered by $date.
So the most recent is at the top and oldest at the bottom.
But only the 5 most recent.

Thanks a lot in advance.
If it's easier.
How would I display the bottom 5 lines of the file (formatted)

- Neil :)

jrap
May 27th, 2001, 18:54
Printing out the last 5 lines would be very easy. Here is an exampe:

test.txt


Name1|time1
Name2|time2
Name3|time3
Name4|time4
Name5|time5
Name6|time6
Name7|time7
Name8|time8
Name9|time9
Name10|time10


code:


#!/usr/bin/perl
my $file = 'C:\windows\desktop\test.txt';

#get contents of file in an array. reversed.
open(IN,$file) or die ("Cannot open $file: $!");
chomp(my @contents = reverse(<IN>));
close(IN);

#print out the first 5 elements of array (last 5 of file)
for(my $i=0;$i<=4;$i++)
{
my($name,$date) = split('\|',@contents[$i]);
print "$name and $date\n";
}


output:


Name10 and time10
Name9 and time9
Name8 and time8
Name7 and time7
Name6 and time6


Hope that helps.