correct • elegant • free

△ comp.lang.perl △

◅ Week numbers

most efficient way to find the LAST line number in a file

In article <61vv2s$8sn$>,
Krishan Purahoo <> wrote:
>What is the most efficient method to get the  LAST line number
>of a file, in perl (no system call).

    $ perl -ne 'END { print $., "\n" }' file

In a longer script, you could use something like this (beware that this
only counts lines if $/ == "\n").

    $line = 0;
    while (<IN>) {

>Reading the file in an array seems to be quite slow

If you don't need the file's contents, then you should throw each line
away after you've read it (as the above examples do).  If you store them
all in an array, then Perl has to allocate enough memory to hold the
entire file!

>Can I use seek for this?

No.  The operating system has no idea how many lines a file contains, it
sees it as merely a string of bytes.  To discover the number of lines in
a file, you must read each of those bytes, and count how many are the
newline character.

Tim Goodwin | "Gateways are designed for the purpose of losing information;
Cygnus, UK  | some do better than others." -- Dave Crocker

Original headers:

From: (Tim Goodwin)
Newsgroups: comp.lang.perl.misc
Subject: Re: most efficient way to find the LAST line number in a file
Date: 14 Oct 1997 15:33:03 GMT
Organization: Cygnus Solutions Ltd, UK
Message-ID: <6203bf$io7$>
References: <61vv2s$8sn$>

△ comp.lang.perl △

◅ Week numbers