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

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 (<>) { ... }

Replies are listed 'Best First'.
Re^3: Which is your favourite cmt-deserving Perl feature?
by merlyn (Sage) on Jul 22, 2005 at 17:03 UTC
    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

        <> needs to hit eof. Try this:

        $ touch empty_file $ yes junk | head -3 | perl nasty.pl empty_file first line: first loop: junk first loop: junk first loop: junk

        Nasty, it is.