Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

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 ( #1039171=note: print w/ replies, xml ) Need Help??


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

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; }


Comment on Re^2: Question on Reading a file inside while and counting no.of lines
Select or Download Code
Re^3: Question on Reading a file inside while and counting no.of lines
by davido (Archbishop) on Jun 16, 2013 at 06:50 UTC

    *head-bonk*

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


    Dave

Re^3: Question on Reading a file inside while and counting no.of lines
by AnomalousMonk (Monsignor) on Jun 16, 2013 at 22:33 UTC
    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'

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1039171]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (13)
As of 2014-08-22 16:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (159 votes), past polls