http://www.perlmonks.org?node_id=909812


in reply to Perl fIle handles

The second one, a lexical file handle, is better (although you can drop the first line). This is because the file handle is scoped and will be automatically closed and destroyed when perl leaves the block that created it.

You can create a lexical file handle from a fileglob by just taking its reference:

my $sh = \*SHAKESPEARE;

But it is best to open the lexical file handle directly, and the three parameter form of open when write mode:

open my $fh, $file or die "Can't open $file::$!";

Replies are listed 'Best First'.
Re^2: Perl fIle handles
by mikeraz (Friar) on Jun 15, 2011 at 17:16 UTC

    But it is best to open the lexical file handle directly, and the three parameter form of open when write mode:

    open my $fh, $file or die "Can't open $file::$!";
    Did you mean
     open my $fh, (some mode string of + < > >>), $file or die "Can't open $file::$!";
    ??


    Be Appropriate && Follow Your Curiosity

      No, actually I just wanted to demonstrate that he could include the my within the open statement, but I can see how you could think I was implying something else. It was up to him to simply read the docs for open to see how to use the three parameter form.

      Also, I'd advise against ever using the three parameter form of open when wanting read mode. It's much better to just let read mode be assumed so you don't risk putting the symbol in the wrong direction and overwriting your file.

      Just my .02

        Also, I'd advise against ever using the three parameter form of open when wanting read mode. It's much better to just let read mode be assumed so you don't risk putting the symbol in the wrong direction and overwriting your file.

        And risk having the second arg contain something scary?
        $file = '> somefile';