tobold.org

correct • elegant • free

△ comp.lang.perl △

◅ Week numbers

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

In article <61vv2s$8sn$1@flex.news.pipex.net>,
Krishan Purahoo <kpur@jet.uk> 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>) {
            ++$line;
    }

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

Original headers:

From: tgoodwin@nan.cygnus.co.uk (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$1@korai.cygnus.co.uk>
References: <61vv2s$8sn$1@flex.news.pipex.net>

△ comp.lang.perl △

◅ Week numbers