in reply to Reading a pipe

When data is piped to your program, you can read it from STDIN, no need to do anything fancy. What you're doing is creating a pipe (see man 2 pipe for more information on the underlying mechanism).

Replies are listed 'Best First'.
Re: Re: Reading a pipe
by ok (Beadle) on Apr 02, 2001 at 22:35 UTC
    In other words,
    while (my $line = <STDIN>) { &do_something_with($line); }

      There appears to be a lot of confusion in this thread. I hope this node will help to clear things up.

      In older versions of Perl, this code:

      while (my $line = <STDIN>) { &do_something_with($line); }
      would exit the while loop early under one condition; when the last line of input is '0', with no trailing newline. The solution to this problem was to add a defined() test around the assignment:
      while (defined(my $line = <STDIN>)) { &do_something_with($line); }
      However, as of perl5.005, the defined() test is performed automatically! Thus, the above two snippets of code would be equivalent.

      Here's what the documentation from perl5.6.0 has to say, in a snippet from perlop :

      The following lines are equivalent: while (defined($_ = <STDIN>)) { print; } while ($_ = <STDIN>) { print; } while (<STDIN>) { print; } for (;<STDIN>;) { print; } print while defined($_ = <STDIN>); print while ($_ = <STDIN>); print while <STDIN>; This also behaves similarly, but avoids $_ : while (my $line = <STDIN>) { print $line } In these loop constructs, the assigned value (whether assignment is automatic or explicit) is then tested to see whether it is defined. The defined test avoids problems where line has a string value that would be treated as false by Perl, for example a "" or a "0" with no trailing newline. If you really mean for such value +s to terminate the loop, they should be tested for explicitly: while (($_ = <STDIN>) ne '0') { ... } while (<STDIN>) { last unless $_; ... }
      (A similar explanation can be found in the 5.005 docs, but I found this one from 5.6.0 to be clearer.)
      If the line ever begins with a 0, my $line = <STDIN> will evaluate to false and the loop will end. You can use a defined() around it or
      while(<STDIN>) { #or just while(<>) &do_something_with($_); }
        If the line ever begins with a 0, my $line = <STDIN> will evaluate to false and the loop will end.

        This is false. Try it.