SPUG: tchrist on my vs. local

Tim Maher/CONSULTIX tim at consultix-inc.com
Fri Feb 18 12:34:36 CST 2000


I've been informed the link on a previous email didn't work. No surpise
there, I was hoping against hope that it would work. Here's the article on
local vs. my, which (as I recall) may be a strategic munging of various
exerpts from perdoc stuff.


In comp.lang.perl.misc, "Dave Kaufman" <davidk at cnct.com> writes:
:I was about to paste some functions from a "require" -ed script into my the
:calling script, and forego the require and the need for two files.  But I
:see that the functions I'm (ripping off) --copying, use local() to declare
:all the variables, whereas I always use my() to avoid namespace collisions
:from inside functions.
local() doesn't declare anything.  Hence your confusion.  
:I'm afeared.  What is the difference between my() and local() ?
Read perlfaq7 about this.  I believe that for each Perl programmer who
understands the difference, there are fully 10,000 who do not.  You are not
alone.  It's very depressing.
:I read the camel book explanation but it sailed right over my pea brain.  
Ok, then don't try to understand, just believe the following:
    NEVER USE local() AT ALL (unless you get a syntax error otherwise),
because it doesn't create a local variable; its name is deceiving. Consider
local deprecated, at least for you.  Use my instead. 
I explain this so many times every day I'm too tired to do it again now.
Well, here; I'll cite myself.
Q:  What's the difference between dynamic and lexical (static) scoping?
Between local() and my()?
A:    local($x) saves away the old value of the global variable $x, and
assigns a new value for the duration of the subroutine, which is visible in
other functions called from that subroutine. This is done at run-time, so is
called dynamic scoping.  local() always affects global variables, also
called package variables or dynamic variables.
      my($x) creates a new variable that is only visible in the current
subroutine.  This is done at compile-time, so is called lexical or
static scoping.  my() always affects private variables, also called lexical
variables or (improperly) static(ly scoped) variables. 
      For instance:
          sub visible {
              print "var has value $var\n";
          sub dynamic {
              local $var = 'local';  # new temporary value for the
              visible();              #  variable called $var
          sub lexical {
              my $var = 'private';    # new private variable, $var
              visible();              # (invisible outside of sub scope)
          $var = 'global';
          visible();                  # prints global
          dynamic();                  # prints local
          lexical();                  # prints global
      Notice how at no point does the value "private" get printed. That's
because $var only has that value within the block of the lexical() function,
and it is hidden from called subroutine. 
      In summary, local() doesn't make what you think of as private, local
variables.  It gives a global variable a temporary value.  my() is what
you're looking for if you want private variables. 
      See also the perlsub manpage, which explains this all in more detail.
And here the referenced section from perlsub:
  Private Variables via my()
          my $foo;            # declare $foo lexically local
          my (@wid, %get);    # declare list of variables local
          my $foo = "flurp";  # declare $foo lexical, and init it
          my @oof = @bar;    # declare @oof lexical, and init it 
      A "my" declares the listed variables to be confined (lexically)
      to the enclosing block, conditional (if/unless/elsif/else),
      loop (for/foreach/while/until/continue), subroutine, eval, or
      do/require/use'd file.  If more than one value is listed, the
      list must be placed in parentheses.  All listed elements must be
      legal lvalues.  Only alphanumeric identifiers may be lexically
      scoped--magical builtins like $/ must currently be localized with
      "local" instead.
      Unlike dynamic variables created by the "local" statement, lexical
      variables declared with "my" are totally hidden from the outside
      world, including any called subroutines (even if it's the same
      subroutine called from itself or elsewhere--every call gets its
      own copy).
      (An eval(), however, can see the lexical variables of the scope
      it is being evaluated in so long as the names aren't hidden by
      declarations within the eval() itself.  See the perlref manpage.) 
      The parameter list to my() may be assigned to if desired, which
      allows you to initialize your variables.  (If no initializer
      is given for a particular variable, it is created with the
      undefined value.)  Commonly this is used to name the parameters
      to a subroutine.  Examples:
          $arg = "fred";        # "global" variable
          $n = cube_root(27);
          print "$arg thinks the root is $n\n";
        fred thinks the root is 3
          sub cube_root {
              my $arg = shift;  # name doesn't matter
              $arg **= 1/3;
              return $arg;
      The "my" is simply a modifier on something you might assign to.  So
      you do assign to the variables in its argument list, the "my" doesn't
      change whether those variables is viewed as a scalar or an array.  So 
          my ($foo) = <STDIN>;
          my @FOO = <STDIN>;
      both supply a list context to the right-hand side, while
          my $foo = <STDIN>;
      supplies a scalar context.  But the following declares only
      one variable:
          my $foo, $bar = 1;
      That has the same effect as
          my $foo;
          $bar = 1;
      The declared variable is not introduced (is not visible) until
      after the current statement.  Thus,
          my $x = $x;
      can be used to initialize the new $x with the value of the old $x,
      and the expression
          my $x = 123 and $x == 123
      is false unless the old $x happened to have the value 123. 
      Lexical scopes of control structures are not bounded precisely
      by the braces that delimit their controlled blocks; control
      expressions are part of the scope, too.  Thus in the loop 
          while (defined(my $line = <>)) {
              $line = lc $line;
          } continue {
              print $line;
      the scope of $line extends from its declaration throughout the
      rest of the loop construct (including the continue clause),
      but not beyond it.  Similarly, in the conditional
          if ((my $answer = <STDIN>) =~ /^yes$/i) {
          } elsif ($answer =~ /^no$/i) {
          } else {
              chomp $answer;
              die "'$answer' is neither 'yes' nor 'no'";
      the scope of $answer extends from its declaration throughout
      the rest of the conditional (including elsif and else clauses,
      if any), but not beyond it.
      (None of the foregoing applies to if/unless or while/until
      modifiers appended to simple statements.  Such modifiers are not
      control structures and have no effect on scoping.)
      The foreach loop defaults to scoping its index variable dynamically
      (in the manner of local; see below).  However, if the index
      variable is prefixed with the keyword "my", then it is lexically
      scoped instead.  Thus in the loop
          for my $i (1, 2, 3) {
      the scope of $i extends to the end of the loop, but not beyond it,
      and so the value of $i is unavailable in some_function(). 
      Some users may wish to encourage the use of lexically scoped
      variables.  As an aid to catching implicit references to package
      variables, if you say
          use strict 'vars';
      then any variable reference from there to the end of the enclosing
      block must either refer to a lexical variable, or must be fully
      qualified with the package name.  A compilation error results
      otherwise.  An inner block may countermand this with "no strict
      A my() has both a compile-time and a run-time effect.  At compile
      time, the compiler takes notice of it; the principle usefulness
      of this is to quiet use strict 'vars'.  The actual initialization
      is delayed until run time, so it gets executed appropriately;
      every time through a loop, for example.
      Variables declared with "my" are not part of any package and
      are therefore never fully qualified with the package name.
      In particular, you're not allowed to try to make a package variable
      (or other global) lexical:
          my $pack::var;      # ERROR!  Illegal syntax
          my $_;              # also illegal (currently)
      In fact, a dynamic variable (also known as package or global
      variables) are still accessible using the fully qualified ::
      notation even while a lexical of the same name is also visible: 
          package main;
          local $x = 10;
          my    $x = 20;
          print "$x and $::x\n";
      That will print out 20 and 10.
      You may declare "my" variables at the outermost scope of a file
      to hide any such identifiers totally from the outside world.
      This is similar to C's static variables at the file level.
      To do this with a subroutine requires the use of a closure
      (anonymous function).  If a block (such as an eval(), function,
      or package) wants to create a private subroutine that cannot be
      called from outside that block, it can declare a lexical variable
      containing an anonymous sub reference:
          my $secret_version = '1.001-beta';
          my $secret_sub = sub { print $secret_version };
      So long as the reference is never returned by any function within
      the module, no outside module can see the subroutine, because
      its name is not in any package's symbol table.  Remember that
      it's not REALLY called $some_pack::secret_version or anything;
      it's just $secret_version, unqualified and unqualifiable. 
      This does not work with object methods, however; all object
      methods have to be in the symbol table of some package to be found. 
      Just because the lexical variable is lexically (also called
      statically) scoped doesn't mean that within a function it
      works like a C static.  It normally works more like a C auto.
      But here's a mechanism for giving a function private variables
      with both lexical scoping and a static lifetime.  If you do want
      to create something like C's static variables, just enclose the
      whole function in an extra block, and put the static variable
      outside the function but in the block.
              my $secret_val = 0;
              sub gimme_another {
                  return ++$secret_val;
          # $secret_val now becomes unreachable by the outside
          # world, but retains its value between calls to gimme_another 
      If this function is being sourced in from a separate file via
      require or use, then this is probably just fine.  If it's all
      in the main program, you'll need to arrange for the my() to be
      executed early, either by putting the whole block above your main
      program, or more likely, placing merely a BEGIN sub around it to
      make sure it gets executed before your program starts to run: 
          sub BEGIN {
              my $secret_val = 0;
              sub gimme_another {
                  return ++$secret_val;
      See the perlrun manpage about the BEGIN function.
  Temporary Values via local()
      NOTE: In general, you should be using "my" instead of "local",
      because it's faster and safer.  Exceptions to this include the
      global punctuation variables, filehandles and formats, and direct
      manipulation of the Perl symbol table itself.  Format variables
      often use "local" though, as do other variables whose current
      value must be visible to called subroutines.
          local $foo;                # declare $foo dynamically local
          local (@wid, %get);        # declare list of variables local
          local $foo = "flurp";      # declare $foo dynamic, and init it
          local @oof = @bar;          # declare @oof dynamic, and init it 
          local *FH;                  # localize $FH, @FH, %FH, &FH  ...
          local *merlyn = *randal;    # now $merlyn is really $randal, plus
                                      #    @merlyn is really @randal, etc
          local *merlyn = 'randal';  # SAME THING: promote 'randal' to
          local *merlyn = \$randal;  # just alias $merlyn, not @merlyn etc 
      A local() modifies its listed variables to be local to the
      enclosing block, (or subroutine, eval{}, or do) and any called from
      within that block.  A local() just gives temporary values to global
      (meaning package) variables.  This is known as dynamic scoping
      .       Lexical scoping is done with "my", which works more like C's
      auto declarations.
      If more than one variable is given to local(), they must be placed
      in parentheses.  All listed elements must be legal lvalues.
      This operator works by saving the current values of those
      variables in its argument list on a hidden stack and restoring
      them upon exiting the block, subroutine, or eval.  This means
      that called subroutines can also reference the local variable,
      but not the global one.  The argument list may be assigned to if
      desired, which allows you to initialize your local variables.
      (If no initializer is given for a particular variable, it is
      created with an undefined value.)  Commonly this is used to name
      the parameters to a subroutine.  Examples:
          for $i ( 0 .. 9 ) {
              $digits{$i} = $i;
          # assume this function uses global %digits hash
          # now temporarily add to %digits hash
          if ($base12) {
              # (NOTE: not claiming this is efficient!)
              local %digits  = (%digits, 't' => 10, 'e' => 11);
              parse_num();  # parse_num gets this new %digits!
          # old %digits restored here
      Because local() is a run-time command, it gets executed every
      time through a loop.  In releases of Perl previous to 5.0, this
      used more stack storage each time until the loop was exited.
      Perl now reclaims the space each time through, but it's still
      more efficient to declare your variables outside the loop. 
      A local is simply a modifier on an lvalue expression.  When you
      assign to a localized variable, the local doesn't change whether
      its list is viewed as a scalar or an array.  So
          local($foo) = <STDIN>;
          local @FOO = <STDIN>;
      both supply a list context to the right-hand side, while
          local $foo = <STDIN>;
      supplies a scalar context.
      A note about local() and composite types is in order.  Something
      like local(%foo) works by temporarily placing a brand new hash
      in the symbol table.  The old hash is left alone, but is hidden
      "behind" the new one.
      This means the old variable is completely invisible via the
      symbol table (i.e. the hash entry in the *foo typeglob) for the
      duration of the dynamic scope within which the local() was seen.
      This has the effect of allowing one to temporarily occlude any
      magic on composite types.  For instance, this will briefly alter
      a tied hash to some other implementation:
          tie %ahash, 'APackage';
              local %ahash;
              tie %ahash, 'BPackage';
              [..called code will see %ahash tied to 'BPackage'..]
                local %ahash;
                [..%ahash is a normal (untied) hash here..]
          [..%ahash back to its initial tied self again..]
      As another example, a custom implementation of %ENV might look
      like this:
              local %ENV;
              tie %ENV, 'MyOwnEnv';
              [..do your own fancy %ENV manipulation here..]
          [..normal %ENV behavior here..]
--tom, who can't believe anyone made it this far.
 Tom Christiansen tchrist at jhereg.perl.com

With a PC, I always felt limited by the software available.  On Unix, I am
limited by my knowledge.  --Peter J. Schoenster <pschon at baste.magibox.net>

 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    POST TO: spug-list at pm.org        PROBLEMS: owner-spug-list at pm.org
 Seattle Perl Users Group (SPUG) Home Page: http://www.halcyon.com/spug/
 SUBSCRIBE/UNSUBSCRIBE: Replace ACTION below by subscribe or unsubscribe
        Email to majordomo at pm.org: ACTION spug-list your_address

More information about the spug-list mailing list