Home > Archive > PERL Beginners > June 2007 > Reading a particular line from a file
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
Reading a particular line from a file
|
|
| Alok Nath 2007-06-20, 7:59 am |
| Hi,
Is it possible to read a particular line by line number ?
For e.g reading line 3 from a file.
I don't want to read each line and count.
Thanks
Alok
| |
| Ken Foskey 2007-06-20, 6:59 pm |
| On Wed, 2007-06-20 at 17:12 +0530, Nath, Alok (STSD) wrote:
> Hi,
> Is it possible to read a particular line by line number ?
>
> For e.g reading line 3 from a file.
>
> I don't want to read each line and count.
No and yes. If it is genuine new random data then no.
If it is fixed length then you can calculate the position and then do a
s to the position. (record length +1) * record number (+2 for cr lf
line endings).
You can index before hand. For example I have a sort process that reads
the file, does a tell for the position of the records, the index is
then manipulated and I can read the records in new order by doing a
s .
--
Ken Foskey
FOSS developer
| |
| Paul Lalli 2007-06-20, 6:59 pm |
| On Jun 20, 7:42 am, alok.n...@hp.com (Alok Nath) wrote:
> Is it possible to read a particular line by line number ?
>
> For e.g reading line 3 from a file.
>
> I don't want to read each line and count.
You don't have to count. Perl counts for you. The current line number
is always stored in the $. variable.
my $third;
while (<$fh> ) {
if ($. == 3) {
$third = $_;
last;
}
}
Alternatively, consider the Tie::File module:
#!/usr/bin/perl
use strict;
use warnings;
use Tie::File;
tie my @lines, 'Tie::File', "file.txt" or die $!;
my $third = $lines[2];
__END__
Paul Lalli
|
|
|
|
|