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


in reply to local vs my

I would now like to use 'use strict' but 'use strict' doesn't regard 'local' as a way of defining a variable, so I get many "... requires explicit package name at..." messages.

That's because local doesn't define variables. It merely changes the value in an already existing package variable.

I remember reading somewhere that 'local' works whereas 'my' doesn't when dealing with file handles... Am I remembering incorrectly? I can't find this.

That's right. Filehandles only ever exist as package "variables" in typeglobs. You have to localise them with local you can't create lexical filehandles with my - although you can now create lexical filehandle objects with syntax like:

my $fh = IO::Handle->new;
I am now considering changing all occurrences of 'local' in the script to 'my' but am worried that this will break the code.

There's a chance that this will break your code. The best way to make your script "strict-clean" is to define all of your variables at the file level with use vars or our.

Are there places where I can read about the differences between 'my' and 'local'?

I like Dominus' articles Coping With Scoping and Seven useful uses of local.

--
<http://www.dave.org.uk>

"The first rule of Perl club is you do not talk about Perl club."
-- Chip Salzenberg

Replies are listed 'Best First'.
Re: Re: local vs my
by Anonymous Monk on Sep 03, 2002 at 07:53 UTC
    That's right. Filehandles only ever exist as package "variables" in typeglobs. You have to localise them with local you can't create lexical filehandles with my

    What about this?

    open(my $fh, 'somefile') || die $!;

      What about this?

      open(my $fh, 'somefile') || die $!;

      When calling open with an undefined variable for the indirect filehandle ($fh in this case), open will stick a reference to the "real" filehandle in the indirect filehandle. $fh is a lexical, what it refers to is not.

      — Arien

      Excellent point. But that is, of course, a relatively new innovation :)

      --
      <http://www.dave.org.uk>

      "The first rule of Perl club is you do not talk about Perl club."
      -- Chip Salzenberg

        The innovation is only in the autovivification. It was awkwardly possible before as well, you just had to do the job yourself:
        use Symbol; my $fh = gensym; open $fh, $filename;

        Makeshifts last the longest.