Well, what's a line?

The first line starts by the beginning of the file and ends at the first LF (or CRLF depending upon your operating system).
Most of the lines will start just after the preceeding line termination and continue to the next line termination (LF or CRLF).
Finally, one line may continue until end of file. This is not really clean, since for a 'true text file', the last byte(s) in the file should be a line terminator.
All of the above for a file that contains at least four lines.

Now, the problem has become to count the number or line terminators in the file and potentially add one to that. ("Until end of file.")

To count occurences of something in a (non indexed) file you will have to read it from the beginning until the end.
You could read the file byte by byte and verify each byte if it's a CR or an LF. If it's a CR, will the next byte be LF? (Assuming DOS/Windows as an OS.)
Why not let the file read figure out what is a line terminator for you? Then read one line at a time, count it and then throw it away.
Using $. is fine if you make some assumptions. $. is reset when the file handle is closed. From perlvar: Because <> never does an explicit close, line numbers increase across ARGV files. Take care.

There are smarter ways of doing it. But then you'll have to start making assumptions on how a line ends. And that the last line actually is correctly terminated. (Well, it should. But...)

f--k the world!!!!
/dev/world has reached maximal mount count, check forced.


In reply to Re: Looking for a better way to get the number of lines in a file... by Biker
in thread Looking for a better way to get the number of lines in a file... by coec

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.