3 ms·
sub foo { if (whatever) { open my $fh, ...; return $fh; } else { return \*STDOUT; } } will do the job.
by shawn_w 2y ago
sub foo {
if (whatever) {
open my $fh, ...;
return $fh;
} else {
return \*STDOUT;
}
}
will do the job.
- akoboldfrying 2y agoThanks. I feel certain that I tried exactly this a long time ago, and it didn't work as expected, but I may be misremembering. I'll give this a shot the next time I'm in front of a keyboard -- if it works, it will be nothing short of healing.
- mst 2y agoSlight oddities converting it into a one-liner but here's a copy and paste from a shell session running in my local WSL slice: demeisen=; perl -e 'my $in_fh = (defined $ARGV[0] and $ARGV[0] ne "-") ? do { open my $fh, "<", $ARGV[0] or die "Failed to open $ARGV[0]: $!"; $fh } : \*STDIN; print "Line: ".<$in_fh>;' HELLO Line: HELLO demeisen=; perl -e 'my $in_fh = (defined $ARGV[0] and $ARGV[0] ne "-") ? do { open my $fh, "<", $ARGV[0] or die "Failed to open $ARGV[0]: $!"; $fh } : \*STDIN; print "Line: ".<$in_fh>;' - HELLO Line: HELLO demeisen=; echo 'HI' >tmp/hi demeisen=; perl -e 'my $in_fh = (defined $ARGV[0] and $ARGV[0] ne "-") ? do { open my $fh, "<", $ARGV[0] or die "Failed to open $ARGV[0]: $!"; $fh } : \*STDIN; print "Line: ".<$in_fh>;' tmp/hi Line: HI demeisen=;