4

I have seen that in perl sometimes to open a file for writing they use:

open(my $file_handle, ">$file_name");

And sometimes:

open(FILE_HANDLE, ">$file_name");

What is the difference?

Mihran Hovsepyan
  • 10,810
  • 14
  • 61
  • 111
  • 4
    From the [Stack Overflow Perl FAQ](http://stackoverflow.com/questions/tagged/perl?sort=faq): [Why is three-argument open calls with lexical filehandles a Perl best practice?](http://stackoverflow.com/questions/1479741/why-is-three-argument-open-calls-with-lexical-filehandles-a-perl-best-practice) – daxim May 06 '11 at 07:02

1 Answers1

14

The first method you showed is the newer, and usually favorable method. It uses lexical filehandles (filehandles that are lexically scoped). The second method uses package-global typeglob filehandles. Their scoping is broader. Modern Perl programs usually use the 'my' version, unless they have a good reason not to.

You ought to have a look at perlopentut (from the Perl documentation), and perlfunc -f open (from the Perl POD). Those two resources give you a lot of good information. While you're there, look up the three argument version of open, as well as error checking. A really good way to open a file nowadays is:

open my $file_handle, '>', $filename or die $!;
DavidO
  • 13,812
  • 3
  • 38
  • 66