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

I'm a bit confused as to how to get the contents of a pipe. I think I want to use IO::Pipe and invoke the reader method. However, when I try
use IO; $pipe=new IO::Pipe; $pipe->reader(); while (<$pipe>){ print "> $_\n"; }
and save it as test.pl and then try cat test.pl|perl test.pl, I get no output.

(Ultimately, I want to set a procmail rule to send certain messages through a perlscript, and procmail wants to send these as a pipe...)

Of course I could be going about this completely wrong. It wouldn't be the first time.

Thanks for any help!

Replies are listed 'Best First'.
Re: Reading a pipe
by Anonymous Monk on Apr 02, 2001 at 21:54 UTC
    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).
      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($_); }