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?
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
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> };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With