in reply to Count number of lines?

This is actually Not Good Code, but one liners from the prompt are good for getting girls

$ perl -e 'open FH,"users.dat";print scalar(map {1} <FH>)," users to d +ate\n"' 653 users to date $

Properly, the open should be checked and the file closed.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re: Re: Count number of lines?
by Kanji (Parson) on Jun 20, 2001 at 07:20 UTC

    I believe Abigail scored the ultimate Perl one-liner to count lines in a file, with (modified to fit the current context)...

      perl -lpe '}{$_="$. users to date"' users.dat

    A little more readable is ...

      perl -lne 'END { print "$. users to date" }' users.dat

        --k.


      For those of you who wondered, as I did, here's what perl -lpe '}{$_="$.users to date"' is doing:

      The -p option wraps your code in the following loop (see perlrun):

      LINE:
        while (<>) {
          ...             # your program goes here
        } continue {
          print or die "-p destination: $!\n";
        }
      

      The code supplied with the -e switch inserts a closing curly brace, creating an empty while BLOCK, followed by an opening curly brace, which makes a bare block after the while block.

      LINE:
        while (<>) { }
        { $_="$. users to date" }
        continue {
          print or die "-p destination: $!\n";
        }
      

      The while loop reads all the input records, the bare block assigns the string including the value of the input record counter to $_, and the continue block prints the string.

Re: Re: Count number of lines?
by mr.nick (Chaplain) on Jun 20, 2001 at 07:22 UTC
    On a large file, that could be a very expensive operation. I'd suggest (in terms of 1 liners)
    perl -ae '1 while <>;print $.' users.dat

    mr.nick ...

      update: I may have my indentation mixed up! I'd still like to know if yours is faster than abigail's though.

      how is this faster than the above? it looks like it's doing the same thing (while through the file and print $.). is there some sort of overhead with a continue block?

      also, is -a doing something special? I'm confused because perl --help says -a    autosplit mode with -n or -p (splits $_ into @F) which doesn't seem to apply here.

      "Argument is futile - you will be ignorralated!"