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.
Edit: I've been informed that the 2-argument form of open
actually does the magic I'm looking for. Unfortunately, it also does some creative interpretation in order to separate the filename from the mode in the second argument. I guess the 3-argument form of open
is 100% magic-free -- it always opens the exact file you tell it to. I'm asking if I can have a single exception for "-"
while still handling every other file name unambiguously.
Should I just stick my code from above into a subroutine/module and stop whining?