http://qs321.pair.com?node_id=76108

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

I want to write a script which captures input from a pipe. E.g.
% echo "bla" | myscript.pl

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: Capturing input from pipe?
by tomhukins (Curate) on Apr 27, 2001 at 18:46 UTC

    A pipe passes the output of one command to the input of another. So, to read the output of your echo command, read from STDIN. An example myscript.pl might be:

    #!/usr/bin/perl print <>;
Re: Capturing input from pipe?
by ariels (Curate) on May 01, 2001 at 14:20 UTC
    If you want to read only the standard input, you can read the predefined filehandle STDIN. For instance, to add line numbers to all lines coming from your pipe, you could do this:
    #!/usr/local/bin/perl -w use strict; while (<STDIN>) { print "$. $_" }

    But almost any program is more useful if it can read either STDIN or filenames supplied on the command line. So reading <> almost always makes more sense.

Re: Capturing input from pipe?
by hdp (Beadle) on Apr 27, 2001 at 19:03 UTC
    Oft-used command line switches related to this subject are -p, -n, and -a (especially in conjunction with -F). See perlrun for how they work and what they do.

    hdp.

Re: Capturing input from pipe?
by lowlife (Initiate) on Apr 27, 2001 at 19:00 UTC
    OK, that was a lot simpler than I thought but it works exactly like I want. Thanks a lot!