Reputation: 6152
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
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