Solved

Use of 'local'

Posted on 2008-06-11
9
157 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
ID: 21763470
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
ID: 21763475
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
ID: 21763550
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
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
LVL 84

Assisted Solution

by:ozo
ozo earned 250 total points
ID: 21763565
#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
 
LVL 84

Expert Comment

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

Expert Comment

by:Tintin
ID: 21766123
0
 
LVL 84

Expert Comment

by:ozo
ID: 21766393
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
ID: 21768548
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
ID: 21773525
yes
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
A year or so back I was asked to have a play with MongoDB; within half an hour I had downloaded (http://www.mongodb.org/downloads),  installed and started the daemon, and had a console window open. After an hour or two of playing at the command …
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…
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.

803 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