in reply to Which is your favourite cmt-deserving Perl feature?

You said it in your original post, but here's the canonical example:

while(<>) { next if 1..1; # skip first line ... }

Replies are listed 'Best First'.
Re^2: Which is your favourite cmt-deserving Perl feature?
by Anonymous Monk on Jul 22, 2005 at 15:25 UTC
    Eeew. Classical example of how not to program. About the first thing I learned when learning how to program efficiently is to take anything out of the loop that doesn't need to be in the loop. If you want to skip the first line, skip it outside the loop, don't test for every line whether it'll be the first line or not.
    <>; # Skip first line. while (<>) { ... }
      Except that this is not an equivalent loop if there is only one line to be read. If you read that one line, @ARGV is now empty, and when you enter the loop, the ARGV loop will now be reading STDIN! Oops! Doh!

      -- Randal L. Schwartz, Perl hacker
      Be sure to read my standard disclaimer if this is a reply.

        That sounds pretty nasty, but I'm having a hard time implementing it, so I'm not sure I'm getting your point. I tried this:

        # nasty.pl use strict; use warnings; $| = 1; print 'first line: ', scalar <>; while (<>) { print "first loop: $_"; } while (<STDIN>) { print "second loop: $_"; } __END__
        and called it with
        % echo 'just another one-line file' > one-line_file % yes junk | head -3 | perl nasty.pl one-line_file first line: just another one-line file second loop: junk second loop: junk second loop: junk
        I was expecting, from what you wrote, that the first loop would read STDIN, but that's not what the output shows (if I remove the second loop, the first loop still doesn't produce any output). What am I missing?

        the lowliest monk

Re^2: Which is your favourite cmt-deserving Perl feature?
by blazar (Canon) on Jul 22, 2005 at 10:40 UTC
    Ouch! Not only this is the .. operator in scalar context, which is somewhat esoteric as of itself, but it is a special case of it which is even more esoteric, and used with both limits equal to 1 which further adds to its esoteric nature! Thus: nice example indeed! And nice golfing technique - I'll keep it in mind. But I guess that I would rather write
    next if $. == 1;
    in most other situations...