Reputation: 8939
I want to be able to read the "next line" without increasing the line counter, so that the next time a read command is isued it will read the same line.
example:
this is the first line
this is the second line
this is the third line
I want to be able to know that the second line says "this is the second line" but not advancing my counter so that my program:
print <>;
print unknown_read_command;
print <>;
will print on the screen:
this is the first line
this is the second line
this is the second line
And in a more general, how can I change and move the pointer to the line in any direction and any amount that I want?
Upvotes: 4
Views: 1444
Reputation: 96974
If you're reading line by line, another way to do this is with Tie::File
:
#!/usr/bin/perl
use strict;
use warnings;
use Tie::File;
my $fn = "foo.bar";
tie my @myFileLines, 'Tie::File', $fn or die "$?";
print STDOUT $myFileLines[0];
print STDOUT $myFileLines[1];
print STDOUT $myFileLines[1]; # print second line twice
untie @myFileLines;
Using file seek methods is more generic and you'll have to search for newline delimiters yourself, which Windows complicates with a proprietary newline.
Upvotes: 3
Reputation: 150111
You can fetch the file position for a filehandle with tell, and set it with seek:
my $pos = tell $fh;
# ...
seek $fh, $pos, 0 or die "Couldn't seek to $pos: $!\n";
Upvotes: 7