baxy77bax has asked for the wisdom of the Perl Monks concerning the following question:

hi,

well this maybe redundant but i'm curious. is there a way to do this from a command line:

open (IN, "<", $ARGV[0]); my $i =0; while (<IN>){$i++} print $i;
so what i'm aiming for is the result of this :
perl -e 'open(IN,"<", $ARGV[0]);$i=0;while(<IN>){$i++};print $i' in.fi +le
but without open(IN,"<", $ARGV[0]); and while. i would like just to say what want and that iteration is assumed so :
perl -ne '$i++; print $i' in.file
so the question is how to preserve the $i in
perl -ne '$i++; print $i' in.file
and print it when iterator reaches the end of the file

something like in awk but in all mighty Perl way !!!!

thnx

baxy

Replies are listed 'Best First'.
Re: one liner - open file and read
by Corion (Patriarch) on Oct 07, 2010 at 17:28 UTC

    See perlrun about the -n and -p switches:

    perl -wnle "$i++;END{print $i}" in.fi

    ... or

    perl -wnle "END{print $.}" in.fi

    ... or just wc -l in.fi.

Re: one liner - open file and read
by jwkrahn (Abbot) on Oct 07, 2010 at 17:55 UTC
      That works, but I don't understand the syntax, or why it works.

      Please enlighten. -- Thanks.

           Syntactic sugar causes cancer of the semicolon.        --Alan Perlis

        perlrun says of -n:

        causes Perl to assume the following loop around your program, which makes it iterate over filename arguments somewhat like sed -n or awk:
        LINE: while (<>) { ... # your program goes here }
        So, perl replaces '...' with jwkrahn's '}{print $.'.

        Make sense now?

Re: one liner - open file and read
by JavaFan (Canon) on Oct 07, 2010 at 18:24 UTC

      Don't re-direct; wc accepts a filename argument, or a list of filenames.

      wc -l in.file # also check out when multiple files match the pattern ... wc *.dat

      As Occam said: Entia non sunt multiplicanda praeter necessitatem.

        I know what wc is capable of.

        Hence the redirect.

        Run it with and without the redirect, and compare it to the output of the OP.