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

I want to be able to read the "next line" without increasing the line counter, so the next time the read command is displayed, it will read the same line.

Example:

this is the first line
this is the second line
this is the third row

I want to know that the second line says "this is the second line", but do not advance my counter to 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 sense, how can I change and move the pointer to a string in any direction and any amount I want?

+4
source share
2 answers

You can get the file position for the file descriptor with tell and set it with seek :

 my $pos = tell $fh; # ... seek $fh, $pos, 0 or die "Couldn't seek to $pos: $!\n"; 
+7
source

If you read line by line, another way to do this is 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 search methods is more general, and you will have to search for line breaks yourself, which Windows makes it difficult to use newlines.

+3
source

All Articles