in reply to Reading from a file
I now need to find a specific line in the file not only the first and last like the example shows(I know the suffix) is there a better way that to run on the (loop) array and find it ?Last I heard (only a few days ago), davido was working on a module for CPAN, to use an index on a text file. You might want to use it when it becomes available.
In the meantime, here's one way you can do it by hand. The assumption is that the original data text file is not changed often.
First, here's how to create the index file:
open IN, "<", $textfile or die "Can't open textfile: $!"; binmode IN; open IDX, ">", "$textfile.idx" or die "Can't create index file: $!"; binmode IDX; print IDX pack "N", 0; while(<IN>) { print IDX, pack "N", tell IN; }
Next, here's how to look up a line by number (in $lineno):
(update: fixed parameter order for seek)open TEXT, "<", $textfile or die "Can't open textfile: $!"; open IDX, "<", "$textfile.idx" or die "Can't open index file: $!"; binmode IDX; seek IDX, 4*$lineno, 0; read IDX, my($buf), 4; seek TEXT, unpack("N", $buf), 0; $line = <TEXT>;
As you may have guessed, the pack/unpack serves to make the integer index a fixed length (4 bytes).
|
|---|