Solved

Use of 'local'

Posted on 2008-06-11
9
155 Views
Last Modified: 2010-03-05
Hi,

It seems that the 'local' keyword isn't used much in perl 5. I just wanted to double-check if my understanding of it is correct.

When you declare a local variable, it replaces the value of a global variable of the same name, until the scope in which is was used is exited, and then it will return the variable back to its global value.

Example:

our $g = 5;

sub a()
{
    local $g = 10;
}

sub b()
{
    print($g, "\n");
}

print($g, "\n");
a();
print($g, "\n");

So the above is going to print:

   5
   10
   5

That's because g, a global, is set to 5 initially. Inside a(), it is re-scoped as a local. So the global value of $g is 'put on the side' temporarily. Now anytime I use $g inside a() or any scope called within a(), it's going to appear as if $g is 10?

Finally when I exit the scope of a(), $g is restored to its original value of 5.

Is that right? It seems like a confusing method.

Thanks
0
Comment
Question by:DJ_AM_Juicebox
9 Comments
 
LVL 84

Expert Comment

by:ozo
Comment Utility
well, the above program doesn't print the 10, but you're right about it printing 5
see
perldoc -f local
local was implemented long before my was created, so it was sort of a stopgap
but it still has use for built in variables
(you can't do my $/; )
0
 
LVL 39

Accepted Solution

by:
Adam314 earned 250 total points
Comment Utility
The code you have will print
    5
    5

The call to sub a doesn't change the value of the global $g.  The local command modifies the listed variables to be local to the enclosing block, file, or eval.
0
 

Author Comment

by:DJ_AM_Juicebox
Comment Utility
Shoot, sorry, you're right, I forgot the call to b(). Please ignore the first post then, this is what I meant for it to be:




our $g = 5;

sub a()
{
    local $g = 10;
    b();
}

sub b()
{
    print($g, "\n");
}


print($g, "\n");
a();
print($g, "\n");


>> The call to sub a doesn't change the value of the global $g
This is what I don't get, so what is the perl interpreter actually doing? Is it making a new variable $g, which is only visible within a() and subs it calls? Therefore since a() calls b(), it only sees the 'local' instance of $g. The global $g never changed.
0
 
LVL 84

Assisted Solution

by:ozo
ozo earned 250 total points
Comment Utility
#this may illustrate the difference between local and my
our $g = 5;

sub a
{
    local $g = 10;
    b();
}

sub b
{
    print($g, "\n");
}

sub c{
   my $g=20;
    b();
}
print($g, "\n");
a();
print($g, "\n");
c();
print($g, "\n");
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 84

Expert Comment

by:ozo
Comment Utility
see
Temporary Values via local()
in
perldoc perlsub
0
 
LVL 48

Expert Comment

by:Tintin
Comment Utility
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
That may be a bit over simplified, but it can still be a useful rule of thumb for beginners until they learn enough to know when it's safe to ignore it.
e.g.
{ local $/ = undef; $slurp = <FILE>; }


see also
perldoc -q "What's the difference between dynamic and lexical \(static\) scoping"
0
 

Author Comment

by:DJ_AM_Juicebox
Comment Utility
Ok from your links, these two definitions seem to agree:

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.

or

First, here's what local $x really does: It saves the current value of the package variable $x in a safe place, and replaces it with a new value, or with undef if no new value was specified. It also arranges for the old value to be restored when control leaves the current block. The variables that it affects are package variables, which get local values. But package variables are always global, and a local package variable is no exception.


So in my own words, when you use local on a global var (you can only use it on a global var), perl puts the original value of the global in a magical place and replaces its value with whatever you set (or undefs it if you didn't set it). Any calls at the scope in which you local'd it, or scopes called from there, will see the replaced global variable, until the scope in which you local'd it exits, then perl replaces it with the value tucked away in the magical place.

I can see how this would be useful without the 'my' keyword.
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
yes
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Email validation in proper way is  very important validation required in any web pages. This code is self explainable except that Regular Expression which I used for pattern matching. I originally published as a thread on my website : http://www…
There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now