Skip to main content
edited tags
Link
muru
  • 78.4k
  • 16
  • 214
  • 320
Source Link
Uwe
  • 3.4k
  • 20
  • 20

perl: Use "-" for standard input with 3-arg open

The old 2-arg version of open (i.e., open FILEHANDLE,EXPR) to open a file in perl is deprecated. For security reasons, it should be replaced by the 3-arg version open FILEHANDLE,MODE,EXPR. There is one case, though, where the 3-arg version behaves differently from the 2-arg version:

2-arg open interprets the special filename - as standard input. For instance, both

echo foo | perl -e 'open my $fh, "-"; $_ = <$fh>; print $_;'

and

echo foo | perl -e 'open my $fh, "<-"; $_ = <$fh>; print $_;'

produce the output foo. In the 3-arg version, the special interpretation of - has disappeared, however:

echo foo | perl -e 'open my $fh, "<", "-"; $_ = <$fh>; print $_;'

prints nothing.

What's the standard or recommended way to emulate this feature of 2-arg open using 3-arg open? (In the concrete application, the filename is an argument of the program which may or may not be -.)