Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I was wondering about the behavior of open when it fails.
open my $fh, '<', 'an_unlikely_file' or print "Not opened\n"; if ($fh) { print "But $fh evaluates to true\n" }
The output I get is,
Not opened But GLOB(0x183f070) evaluates to true
This may not be unexpected, but it doesn't agree with my intuition from C, where filehandles are NULL when fopen fails. Could someone share their insights about this behavior in Perl?

Replies are listed 'Best First'.
Re: Filehandles when Open Fails
by jasonk (Parson) on Jul 25, 2007 at 14:44 UTC

    The documentation says:

    If FILEHANDLE is an undefined scalar variable (or array or hash element) the variable is assigned a reference to a new anonymous filehandle
    So this means that when you say open my $fh, ..., it is essentially the same as this:

    my $fh = \*ANON; open( $fh, "...");

    Since the anonymous filehandle is really created before the open, it will still exist even if the open fails...


    We're not surrounded, we're in a target-rich environment!
Re: Filehandles when Open Fails
by cdarke (Prior) on Jul 25, 2007 at 15:06 UTC
    my intuition from C, where filehandles are NULL when fopen fails

    That's because fopen returns the "file handle": it can only use that to indicate an error, all the arguments are const. C has no choice. If you think about it, perl open returning false on error is the same as C fopen, which also returns false on error.
Re: Filehandles when Open Fails
by Joost (Canon) on Jul 25, 2007 at 21:09 UTC
    Hah. Well it doesn't agree with my intuition either, but note that the handle you're getting from a failed open acts the same as a closed filehandle, which makes some kind of sense:

    #!/usr/bin/perl -w use strict; open my $fh,'<','does not exists' and die "This file should not exist" +; print <$fh>; close $fh; open $fh, '<','exists.txt' or die "Not opened: $!\n"; close $fh; print <$fh>;
    output if 'exists.txt' exists:
    readline() on closed filehandle $fh at test.pl line 4. readline() on closed filehandle $fh at test.pl line 9.