Reading from pipe or from stdin, how?

D

DaLoverhino

Hello. I have a program where you specify the name of the file you
want to read from command line. But, I want to modify it so that if
no file is specified, it reads from stdin. so here's a code snippet:

my $file = "";

# Parse command line to get file option.
open( FILE, "<", $file) or die "Could not open $file\n";

my $line;

while( ($file && $line = <FILE> ) ||
(!$file && $line = <STDIN>)) {
do_big_loop_here;
}

This doesn't seem to work:

Unix> echo "blah" | ./pxmlgrep
Value of <HANDLE> construct can be "0"; test with defined() at ./
pxmlgrep line 233.
Can't modify logical and (&&) in scalar assignment at ./pxmlgrep line
234, near "<FILE> )
"
Execution of ./pxmlgrep aborted due to compilation errors.

Any suggestions?

thanks.
 
J

Jim Gibson

DaLoverhino said:
Hello. I have a program where you specify the name of the file you
want to read from command line. But, I want to modify it so that if
no file is specified, it reads from stdin. so here's a code snippet:

The null file handle <> has just that behavior. See 'perldoc perlop'
and search for "I/O Operators".

You can use the following while loop in your program:

while(<>) {
...
}

to do what you want. The elements of @ARGV are used as file names to
read. If empty, standard input will be read. You can also use "-" as a
file name to read standard input. You can manipulate the contents of
@ARGV before the loop to specify the files to read.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,563
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top