Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

file-io

perl

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?

like image 489
nsbm Avatar asked Dec 19 '25 11:12

nsbm


2 Answers

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
like image 140
daxim Avatar answered Dec 22 '25 06:12

daxim


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> };
like image 26
mob Avatar answered Dec 22 '25 05:12

mob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!