nsbm
nsbm

Reputation: 6152

Set the line to be read in Perl IO::File

How can I change the position of the pointer in a file handle in terms of line number (not bytes)?

I want to set the first line to beginning reading a file. What is the proper way to do this?

Upvotes: 3

Views: 2085

Answers (2)

mob
mob

Reputation: 118635

Use tell and seek to read and write the position of each line in your file. Here's a possible solution that requires you to pass through the whole file, but doesn't require you to load the whole file into memory at once:

# make a pass through the whole file to get the position of each line
my @pos = (0);   # first line begins at byte 0
open my $fh, '<', $the_file;
while (<$fh>) {
    push @pos, tell($fh);
}
# don't close($fh)


# now use  seek  to move to the position you want
$line5 = do { seek $fh,$pos[4],0; <$fh> };

$second_to_last_line = do { seek $fh,$pos[-3],0; <$fh> };

Upvotes: 4

daxim
daxim

Reputation: 39158

Setting the file pointer is not a purpose to itself. If you want to read a certain line, use Tie::File.

use Tie::File qw();
tie my @file, 'Tie::File', 'thefilename' or die $!;
print $file[2]  # 3rd line

Upvotes: 8

Related Questions