CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Sorting records

 



darian
Deleted

Jan 24, 2000, 5:25 AM

Post #1 of 3 (873 views)
Sorting records Can't Post

I need to be able to open a text file that is formatted like so:
1|John|Doe|30|male
2|Jane|Doe|29|female

I need to make sure that when displayed they are in numerical order according to the first column. I also would like to find a good way to page out the listings so that there are say only 5 per page. Thanks


Borderline
Deleted

Jan 25, 2000, 9:12 AM

Post #2 of 3 (873 views)
Re: Sorting records [In reply to] Can't Post

If you need this much control on the sorting of the information in your text file I recommend you move the information to a Database.
You can use a local Database with the module DB_File if you do not have access to an SQL server. This will make your life a lot easier.
Quick example of using DB_File
<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

#!/usr/bin/perl -w

use strict;
use DB_File;

my @data;
tie @data, 'DB_File', 'file.db', O_CREAT|O_RDWR, 0666, $DB_RECNO
or die 'Could not tie file.db: $!';
$data[0] = 'john|doe|30|male';
$data[1] = 'jane|doe|29|female';
untie @data;
</pre><HR></BLOCKQUOTE>
Now all the data is stored in a database named file.db.To access the info you just tie anouther array to the file. Remember what ever you do to the array will be done to the file. See perldoc DB_File for more info.

HTH
Scott


ljfaraci
Deleted

Jan 27, 2000, 8:04 AM

Post #3 of 3 (873 views)
Re: Sorting records [In reply to] Can't Post

my $Infile = '/dir1/dir2/somefile';
my %Array = ();
my $Zpad = 10;

# use $Zpad for sort key length:
# needs to be larger than longest number expected

open (FILE1, $Infile) or die "Can't open file.";

# Load local list
@records = <FILE1>;
close FILE1;

foreach $rec (@records)
{
# extract the first piece of the record to make it a key
$reckey = substr ($rec, 0, index ($rec, '|'));

# pad it with leading zero's to a max length
$reckey = substr ((10**$Zpad), 1, ($Zpad - length ($reckey))) . $reckey;

# load the sort array using $reckey as the key
$Array {$reckey} = $rec;
}

# process the array using the sort function
$cntr = 1;
foreach $reckey (sort (keys (%Array)))
{
$rec = $Array {$reckey};
print "$rec\n";
if (++$cntr > 5) # pagination
{
print chr (11);
$cntr = 1;
}
}
exit;

Hope this helps...

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives