[ABE.pm] Proper open() syntax?
Tom Freedman
tfreedman at iqep.com
Fri Aug 18 19:55:05 PDT 2006
Hi all,
Yesterday I was working on a little utility to reformat some data files
for import into a different database. While working on the script, I
wanted to see the output directly, rather than have to keep switching to
my editor to see the changes in the output file. I figured, "Hey, I'll
just default the output to STDOUT, or use the second argument as a
filename". Now, I don't write a whole lot of command line scripts, as I
do mostly CGI, so I wasn't quite sure how to best go about it. My first
attempt was:
==START CODE==
use strict;
use warnings;
my $output_file;
open($output_file, '>', $ARGV[1] || STDOUT) or die "$!";
#--later--
print $output_file "$data\n";
==END CODE==
This didn't work. I got a 'Bareword "STDOUT" not allowed while "strict
subs" in use' error. Putting quotes around 'STDOUT' just resulted in
the creation of a file named 'STDOUT' that contained my data.
I got around the problem with this:
==START CODE==
my $output = '>' . ($ARGV[1] || '-');
open($output_file, $output) or die "$!";
==END CODE==
Now, the above works fine, but I don't understand why the first version
didn't work. Is there a way to open STDOUT with the three-arg version
of open()?
For the sake of completeness, I know there are several other methods I
could have employed here, from using select() to change the default
output channel for print() (I find that a bit too clever for such a
simple script) to using a logger module (which I think would be
overkill). Is there some standard idiom for this? Defaulting to STDOUT
in lieu of a named output file shouldn't be such an odd thing to do,
methinks.
Thanks,
Tom
P.S. - All the Mac talk makes me nostalgic for my PowerMac 9500 w/ MacOS
8!
More information about the ABE-pm
mailing list