jake9115
jake9115

Reputation: 4084

How to pipe stdin into a perl script that is looking for input as the only parameter?

This question was necessitated out of laziness on my part, because I have dozens of scripts that are executed in the simple structure:

perl my_script.pl my_input_file

...and the output is printed to stdout. However, now I realize that I have certain situation in which I would like to pipe input into these scripts. So, something like this:

perl my_script.pl my_input_file | perl my_next_script.pl | perl third_script.pl > output

Does anyone know of a way to do this without recoding all of my scripts to accept stdin instead of a user-defined input file? My scripts look for the filename by a statement like this:

open(INPUT,$ARGV[0]) || die("Can't open the input file");

Thanks for any suggestions!

Upvotes: 15

Views: 17296

Answers (2)

TLP
TLP

Reputation: 67900

mpapec has provided the simplest solution. I would like to recommend the diamond operator: <>.

In a script where you would do

open my $fh, "<", $ARGV[0] or die $!;
while (<$fh>) { 
    ... 

You can use the diamond operator to replace most of that code

while (<>) {
    ...

The file handle name will be ARGV if you use argument file names, or STDIN if not. The file name will be found in $ARGV.

This operator invokes a behaviour where Perl looks for input either from file name arguments, or from standard input.

Which means that whether you do

inputpipe | script.pl

or

script.pl inputfile.txt

The diamond operator will take the input just fine.

Note: Your open statement is dangerous. You should use three argument open with explicit mode, and lexical file handle. The die statement connected to it should contain the error variable $! to provide information about why the open failed.

Upvotes: 11

mpapec
mpapec

Reputation: 50637

Use - as filename

perl my_script.pl my_input_file | perl my_next_script.pl - | perl third_script.pl - > output

Upvotes: 17

Related Questions