Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a line from a file without advancing the line counter with Perl

Tags:

perl

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?

like image 437
SIMEL Avatar asked Dec 29 '22 05:12

SIMEL


1 Answers

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";
like image 152
Eugene Yarmash Avatar answered Jan 21 '23 09:01

Eugene Yarmash