When opening a file in perl, how can I automatically use STDIN/OUT if the file name is "-"?

Posted by Ryan Thompson on Stack Overflow See other posts from Stack Overflow or by Ryan Thompson
Published on 2010-04-06T19:13:01Z Indexed on 2010/04/06 19:33 UTC
Read the original article Hit count: 289

Filed under:
|

I have a perl program that takes input and output file arguments, and I'd like to support the convention of using "-" to specify standard input/output. The problem is that I can't just open the file name, because open(my $input, '<', '-') opens a file called -, not standard input. So I have to do something like this:

my $input_fh;
if ($input_filename eq '-') {
    # Special case: get the stdin handle
    $input_fh = *STDIN{IO};
}
else {
    # Standard case: open the file
    open($input_fh, '<', $input_filename);
}

And similarly for the output file. Is there any way to do this without testing for the special case myself? I know I could hack the ARGV filehandle to do this for input, but that won't work for output.

© Stack Overflow or respective owner

Related posts about perl

Related posts about input-output