9

The following does not die:

open my $in, '<', undef or
    die q{couldn't open undef};
print <$in>;

Neither does this:

open my $out, '>', undef or
    die q{couldn't open undef};
print $out 'hello';

I don't understand why neither of these die. How could opening undef possibly be successful? The reason I found this was that a guy I work with had done this:

open my $out, '>', $ARGV[0] or die q{couldn't open $ARGV[0]};

He thought that this would kill the script if no arguments were passed in (I know this isn't the cleanest way to do that but I didn't think it wouldn't work).

I'm using Strawberry 5.16.1.

1

1 Answer 1

13

See perldoc -f open:

As a special case the three-argument form with a read/write mode and the third argument being undef:

open(my $tmp, "+>", undef) or die ...

opens a filehandle to an anonymous temporary file.

6
  • 2
    I thought that too, but it's not being opened read/write. I suspect it's undocumented behavior related to this but am not certain of that.
    – Oesor
    Commented Nov 22, 2013 at 22:05
  • I can confirm that Perl 5.10.1 and 5.18.1 both behave this way, with '>' as well as '+>'. It might be interesting to know which versions of Perl do this.
    – Jander
    Commented Nov 22, 2013 at 22:09
  • 5
    @Oesor It works for all modes: read-only, write-only, read-write. In any case opens a an anonymous temporary file. But read-only or write-only modes have no practical application. Commented Nov 22, 2013 at 22:15
  • Maybe I'll send a documentation patch for that, then.
    – Nate Glenn
    Commented Nov 23, 2013 at 0:34
  • I'm not sure that's a behaviour Perl should be committed to providing by documenting it.
    – ikegami
    Commented Jan 22, 2017 at 2:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.