Three options for you:
- Build an index of line numbers to offsets.
- Use DB_File's DB_RECNO interface to tie the text
file to a hash.
- Read through the file each time.
Indexing is easy (code untested, as usual. You can
find tested similar code in the Perl Cookbook):
open(IDX, "> index") or die;
open(DAT, "< datafile") or die;
$pos = 0;
do {
printf IDX "%8d" $pos;
$line = <DAT>;
$pos = tell(DAT);
} while (defined $line);
close(IDX);
close(DAT);
and to use it:
open(IDX, "< index") or die;
open(DAT, "< datafile") or die;
# assume $lnum is the line number to go to
seek(IDX, 8*$lnum, 0) or die;
read(IDX, $offset, 8) or die;
seek(DAT, $offset, 0) or die;
# now DAT filehandle is positioned to read the
# record you wanted
The DB_RECNO interface from DB_File is certainly easier
to use, but it's probably not as efficient as it can't
keep the index on disk as my code here does.
Hope this gives you some pointers.
Nat | [reply] [d/l] [select] |
Another thing you can do is use DBD::RAM to do SQL queries against flat files. It would make life much simpler to issue a simple query as opposed to coding everything manually. | [reply] |
if i had any votes left today, i would spend them ALL
on this message :) ... i didn't know about this one
thanks
| [reply] |
I am not positive what you are asking here, but if I understand correctly, when someone is on 'form 2' you want to show the second record, 'form 3' the third, etc...
I'm not sure how practical it is (since I do not know how many records the file holds) but you could read the file into an array and show the appropriate record by the indicies of the array. If you have fixed length records you could use seek(), etc... to read a certain amount of bytes from a certain place in the file to only read in the record you want. I find this hard to answer without knowing the type of records, the number of records, and if these records are static (as well as if there will often be new records). Why not use a database (out of curiosity)?
Cheers,
KM | [reply] |
Perhaps you could keep a record of the line number that you're currently displaying and create previous and next buttons which set a CGI parameter for the previous and next lines. You CGI script could then read through the file using $. to check when it's on the right line and display the data found on that line.
--
<http://www.dave.org.uk>
European Perl Conference - Sept 22/24 2000
<http://www.yapc.org/Europe/>
| [reply] |