Search code examples
perlfile-ioundefined

why can I open undef?


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.


Solution

  • 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.