3

I have below Perl code.

use warnings;
use strict;

my $x = "global\n";



sub a {
    print $x;
}

sub b {
    local $x = "local\n";
    a();
}

a();
b();
a();

Even if $x has scope inside b() subroutine why Perl doesn't allows to localize it ?

thatisvivek
  • 875
  • 1
  • 12
  • 30

2 Answers2

4

You cannot mix the lexical scope used by my with the namespaced global scope of package variables (the keyword local may only be used on the latter). Perl will treat $x in the source as the lexically-scoped variable once you have defined it as such. You can still access the package variable (using $::x) - although that would just mean you had two entirely separate variables in use, and would not allow you to refer to either at the same time as $x.

You can achieve something very similar to what you appear to be trying to do by using our instead of my:

our $x = "global\n";

The our keyword creates a lexically-scoped alias to a package variable.

Output is then:

global
local
global
Neil Slater
  • 26,512
  • 6
  • 76
  • 94
  • 1
    you should explicitly mention that `local` only affects package variables – ysth Nov 24 '13 at 15:58
  • @Neil Slater: Thanks for your answer. Yes, I know that only global variables are localized, I just wanted to know what is the motivation behind this constraints. – thatisvivek Nov 24 '13 at 16:06
  • 1
    @vivek ratnaparkhi: I'm not sure of the *motivation*, but there are likely to be logical inconsistencies when combining local and lexical scopes, or perhaps performance issues if the Perl interpreter cannot make assumptions about location of data in lexically-scoped variables. Most likely it is possible in principle, but would take effort to support (i.e. the restriction is not arbitrary, but protects code that could not support the behaviour) and be of questionable value. – Neil Slater Nov 24 '13 at 16:17
4

I just wanted to know what is the motivation behind this constraints.

my is thought of as a creator of statically scoped variables.

local is thought of as a creator of dynamically scoped variables.

So you have two similarly-named variables in your program. Given the whole point of my was to replace local, of course my takes precedence over local and not the other way around. You would lose the benefits of my if it was the other way around.

ikegami
  • 367,544
  • 15
  • 269
  • 518