When opening a file in perl, how can I automatically use STDIN/OUT if the file name is "-"?
- by Ryan Thompson
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.