How do you check the success of open (file) in Perl?

From perldoc:

Open returns nonzero on success, the undefined value otherwise.

An often used idiom is

open my $fh, '<', $filename or die $!;

Of course you can do something else than simply die.


open returns a non-zero value on success, and a "false" value on failure. The idiom you are looking for is

if (open my $fh, '>', $file) {
    # open was successful
} else {
    # open failed - handle error
}

If the first argument ($fh) is undefined (as it is in this case), open will initialize it to some arbitrary value (see the Symbol::genysm method) before it attempts to open the file. So $fh will always be "true" even if the open call fails.


$fh isn't being set to a zero-ish value, it is being set to a GLOB as your code shows. This is different from what open returns which is why the idiom is

open(...) or die ... ;

or

unless(open(...)) {
    ...
}

In addition to the explanations in the other answers:

Check out the autodie module which comes with perl 5.10.1 and up (and is available separately from CPAN).

Tags:

File Io

Perl