Hemant Bhargava Hemant Bhargava - 1 year ago 85
Perl Question

How to get the global variable value in Perl?

Trying to understand scope resolution operator.

$a = 5;
print "Out a = $a\n";

sub foo() {
local $a = 10;

sub bar() {
print "Inside a = $a\n";
print "Global a = $::a\n";

Output from this program is :

Inside a = 10
Global a = 10
Out a = 5

  1. I would have expected value of '$::a' to come out as '5' instead of 10. I thought that is what scope resolution operator do. Getting scoped values. In this case, no scope is given, so global value. Please correct me if there is any tweak.

  2. What should I write to get the global value of 'a' inside bar subroutine?

Answer Source

You are misunderstanding ::. Perl doesn't really have global variables (leaving aside certain special identifier names); it has package variables. That is, every global variable belongs to a package. If your code has no package statement, that package is main, so $a is the same as $main::a. And having nothing before the :: is shorthand for main, so $::a is also $main::a.

If you do have a package declaration, package variables used within its scope will be contained in that package unless qualified with ::.

local gives a package variable or hash or array element a temporary value and saves the previous value to be restored when the innermost scope is left. There is no way to access that saved value from within the scope of the local.

The opposite of global/package variables are lexical variables. You almost always will want to use lexical variables (declared with my), not package variables. Even when you do use package variables, you will hardly ever want to change their value with local. So a good case for using local is going to be truly rare.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download