In my Perl script, I would like to process lines from either STDIN or a given file, if specified, as common with Linux/UNIX command line utilities.
To this end, I have the following section in my script (simplified for the post):
use strict;
use warnings;
my $in = \*STDIN;
open $in, '<', $ARGV[0] or die if (defined $ARGV[0]);
print while (<$in>);
Essentially, I define $in to be a reference to the STDIN typeglob, so normally, if no argument is specified, the script does print for each line of <STDIN>. So far, so good.
If $ARGV[0] is defined however, I would like to read lines from that. That is what the second meaningful line purports to do. However, it seems that no lines are processed when ran with an argument.
I noticed that after my conditional call to open, $in does not change, even when I expect it to;
my $in = \*STDIN;
print $in, "\n";
open $in, '<', $ARGV[0] or die if (defined $ARGV[0]);
print $in, "\n";
yields
GLOB(0xaa08b2f4f28)
GLOB(0xaa08b2f4f28)
even when $ARGV[0] is defined. Does open not work when the first variable passed is already referring to a filehandle?
The relevant documentation does include the following
About filehandles
The first argument to open, labeled FILEHANDLE in this reference, is usually a scalar variable. (Exceptions exist, described in "Other considerations", below.) If the call to open succeeds, then the expression provided as FILEHANDLE will get assigned an open filehandle. That filehandle provides an internal reference to the specified external file, conveniently stored in a Perl variable, and ready for I/O operations such as reading and writing.
Based on this alone, I do not see why my code would not work.