Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't localize lexical variable in Perl?

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 ?

like image 634
thatisvivek Avatar asked Oct 18 '25 14:10

thatisvivek


1 Answers

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
like image 198
Neil Slater Avatar answered Oct 20 '25 16:10

Neil Slater