in reply to FileHandle: undef vs close

I'd say they do equivalent things. When a file handle has goes out of scope (or has no more references to it), it is automatically closed. undefing it will drop its refcount to zero, which is why it automatically closes.

I believe you would see the same behavior if you had done a simple open my $fh, "r".

At any rate, they aren't identical, but the outcome is the same. I would recommend using close, but only because I think its intent is more clear.

Replies are listed 'Best First'.
Re^2: FileHandle: undef vs close
by Utilitarian (Vicar) on Apr 30, 2009 at 15:20 UTC
    Forgive my ignorance, but do you know if using undef leaves the closure of the file handle to garbage collection rather than executing the system call straight away and so is undef more efficient? Just wondering.

      You're doing IO and a system call and this is a micro-optimization, so this is a lousy place to optimize, but if you want to close the filehandle unambiguously, use close directly. undef removes one reference count from the filehandle; other variables may point to the same filehandle and prevent Perl's GC from reclaiming it (and closing it implicitly).

      Of course, if other variables point to the same filehandle and you close it explicitly underneath them, you may cause other problems.

Re^2: FileHandle: undef vs close
by vinoth.ree (Monsignor) on Apr 30, 2009 at 14:31 UTC

    Thanks!!

    Vinoth,G