in reply to seek question

I can't say I've ever run across an if() statement used as such, I assume that it's doing a if ($. == 1) from 1 to 3 implicitly, but I'm unsure.

One thing I do know is that seek does not reset the line number variable $. when positioning back to the beginning of the file, so you have to set it explicitly:

use warnings; use strict; my $f = "/etc/fstab"; open ( my $fh, "<", $f ); while ( <$fh> ) { print "$.: $_"; } print "=" x 78, "\n\n"; print "after 1st while loop\n"; seek( $fh, 0, 0); # reset line num $. = 0; while ( <$fh> ) { print if (1..3); }

Replies are listed 'Best First'.
Re^2: seek question
by kcott (Archbishop) on Feb 10, 2017 at 06:42 UTC

    G'day stevieb,

    OP wrote:

    "... if (1..3) ..."

    You wrote:

    "I can't say I've ever run across an if() statement used as such, I assume that it's doing a if ($. == 1) from 1 to 3 implicitly, but I'm unsure."

    From "perlop: Range Operators":

    "If either operand of scalar ".." is a constant expression, that operand is considered true if it is equal (==) to the current input line number (the $. variable)."

    — Ken

Re^2: seek question
by Marshall (Canon) on Feb 09, 2017 at 21:34 UTC
    The seek() function deals with bytes. It knows nothing at all about "lines" or line numbers.

    Of course in this case, you could close the file and then re-open it to reset the $. line counter. I've never had to do that, but it would work.

      I understand that, but OP was looping over the file handle which does use $.. I just meant that seek() does not reset this when going back to first row, first column, so that has to be done manually.

      I concur that closing/re-opening the handle would have the same effect as $. = 0;.