in reply to Question on Reading a file inside while and counting no.of lines

So your immediate problem would be solved by preincrementing instead of postincrementing, so that the incrementing happens before you print.

But your code could be simplified further by using $., documented in perlvar.

while( <FH> ) { print "$.:$_"; }

It starts at zero, so if you need it to start counting at some other base you'll have to add.

print $. + 1, ":$_";

Dave

Replies are listed 'Best First'.
Re^2: Question on Reading a file inside while and counting no.of lines
by Jim (Curate) on Jun 16, 2013 at 02:06 UTC
    It starts at zero…

    Actually, it starts at 1, not 0.

    C:\strawberry>perl -nE "say $." README.txt | head 1 2 3 4 5 6 7 8 9 10 C:\strawberry>

    It's probably also worth demonstrating here the usual idiom for resetting the line number to 1 for each file in @ARGV when using <>.

    # @ARGV may have more than one file in it while (<ARGV>) { print "$.:$_\n"; } continue { close ARGV if eof; }

      *head-bonk*

      Ever since the alien abduction I've had a hard time remembering that $. is 1-based. ;)


      Dave

      It starts at zero...

      Quoth perlvar (emphases added): Each filehandle in Perl counts the number of lines that have been read from it. ... When a line is read from a filehandle (via "readline()" or "<>") ... $. becomes an alias to the line counter for that filehandle.

      So I would say davido's assertion is not without justification:  $. starts out undefined (which is very like zero) and happily becomes 1 by aliasing when the first line is read. I assume the internal filehandle line counter is 0 or undefined prior to any read on the handle. So there.

      >perl -wMstrict -le "my $filename = 'text'; open my $fh, '<', $filename or die qq{opening '$filename': $!}; ;; print qq{\$. initially: }, defined $. ? qq{'$.'} : 'undefined'; ;; while (<$fh>) { chomp; print qq{$.: '$_'}; } ;; close $fh or die qq{closing '$filename': $!}; " $. initially: undefined 1: 'now is the time' 2: 'foo bar baz' 3: 'how now brown cow' 4: 'four score and seven'