How does the difference between "my" and "local" interact with symbolic references? - perl

Previously I read related content in the book of "Effective Perl Programming", but didn't really understand it. Today, I encountered a problem about this, as below code.
my $vname = "a";
my #a = qw(1 2 3);
local #array = #$vname;
foreach(#array) { print "$_\n"; };
It output nothing. Then I modified this line:
local #a = qw(1 2 3);
Just replaced "my" with "local", then it works now. So I'd like to figure out what's the difference between them.

There is a perldoc entry which answers this question in perlfaq7:
What's the difference between dynamic and lexical (static) scoping? Between local() and my()?
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.
my($x) creates a new variable that is only visible in the current
subroutine. This is done at compile-time, so it is called lexical or
static scoping. my() always affects private variables, also called
lexical variables or (improperly) static(ly scoped) variables.
For instance:
sub visible {
print "var has value $var\n";
}
sub dynamic {
local $var = 'local'; # new temporary value for the still-global
visible(); # variable called $var
}
sub lexical {
my $var = 'private'; # new private variable, $var
visible(); # (invisible outside of sub scope)
}
$var = 'global';
visible(); # prints global
dynamic(); # prints local
lexical(); # prints global
Notice how at no point does the value "private" get printed. That's
because $var only has that value within the block of the lexical()
function, and it is hidden from the called subroutine.
In summary, local() doesn't make what you think of as private, local
variables. It gives a global variable a temporary value. my() is what
you're looking for if you want private variables.
See Private Variables via
my() in perlsub
and Temporary Values via
local() in perlsub
for excruciating details.

my creates a new variable. It can only be seen in the lexical scope in which it is declared.
local creates a temporary backup of a global variable that's restored on scope exit, but does not reduce its scope (it can still be seen globally). It does not create a new variable.
You always want to use my when possible, but local is a decent approximation when you have to deal with global variables (e.g. $_).

There are two kinds of variable scopes in Perl:
Global variables: They reside in the current package, can be accessed from the outside and can have "local" values. The name can be used as a key in the "stash", the package variable hash / the symbol table.
Lexical variables: They reside in the current scope (roughly delimited by curly braces). There is no symbol table that can be inspected.
Lexical variables and global variables do not interfere, there can be two different variables with the same name.
Most Perl variable magic happens with global variables. The following syntax works with global variables:
our $var;
$::var;
$main::var;
${'var'};
local $var;
but not my $var.
So we can write:
#::array = qw(a b c);
my #secondArray = #{array};
Which copies the arrays. We can also look up the array with a name that is stored in a variable:
#::array = qw(a b c);
my $name = "array";
my #secondArray = #{$name};
The last line abbreviates to … = #$name.
This is not possible with lexical vars because they do not reside in the stash.
The local function assigns a "local" value to a global variable (and globals only) within the current scope and in the scope of all subs that are called from within this scope ("dynamic scope").
Originally (in Perl 4) meddling with variable names and the stash was the only way to simulate references. These usages are now mostly outdated by ~2 decades as references are available (what is far safer).

I would like to focus on the main cases when you would use them :
my should be your "default" for variables that you wish to keep restricted to a specific block. This should be most of the time
local is useful if you wish to use a global variable, particular one of the special variables. For example
local $/; # enable "slurp" mode
local $_ = <$some_file_handle>; # whole file now here
Using local prevents your change from affecting other code (including modules you didnt write)

In your case, the difference is that local addressed a variable in the symbol table and my does not. This is important because of how to use it:
local #array = #$vname;
That is, you're using $vname as a symbolic reference (a questionable practice absent no strict 'refs' to tell us you know what you're doing). Quotha:
Only package variables (globals, even if localized) are visible to
symbolic references. Lexical variables (declared with my()) aren't in
a symbol table, and thus are invisible to this mechanism.
So symbolic references can only refer to variables in the symbol table. Whether you declare #a as lexical with my or as global with local, #$vname only ever refers to #main::a. When you say
local #a = qw(1 2 3);
, you are giving a new value to #main::a. When you say
my #a = qw(1 2 3);
, you are creating a new lexical variable #a and giving it a value, but leaving #main::a undefined. When
local #array = #$vname;
then accesses the value of #main::a, if finds it to be undefined and sets the value of #array to it.
If all that seems confusing, that's because it is. This is why you are strongly encouraged to use strict and warnings (which would have exploded prettily on this code) and discouraged from using symbolic references unless you really know what you're doing.

Related

How to get the global variable value in Perl?

Trying to understand scope resolution operator.
$a = 5;
foo();
print "Out a = $a\n";
sub foo() {
local $a = 10;
bar();
}
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
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.
What should I write to get the global value of 'a' inside bar subroutine?
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.
Well, first off - don't use $a - single letter variable names are generally nasty, and that goes double for when it's used by sort.
Secondly local doesn't do what you think it does. It even says in the man page:
You really probably want to be using my instead, because local isn't what most people think of as "local". See Private Variables via my() in perlsub for details.
A local modifies the listed variables to be local to the enclosing block, file, or eval. If more than one value is listed, the list must be placed in parentheses. See Temporary Values via local() in perlsub for details, including issues with tied arrays and hashes.
So you probably want to use my, but... actually, more likely, you probably just want to not do that, and don't use globals at all.
#!/usr/bin/env perl
use strict;
use warnings;
our $number = 5;
foo();
print "Out number = $number\n";
sub foo {
my $number = 10;
print "Inside foo: $number\n";
print "Global foo $::number\n";
bar();
}
sub bar {
print "Inside bar = $number\n";
print "Global $::number\n";
}
As you can see - $number is lexically scoped to be "within foo" and doesn't persist into b.
Inside foo: 10
Global foo = 5
Inside a = 5
Global a = 5
Out number = 5
Thirdly - don't use prototypes on your subs. They don't do what you think they do.

Perl lexically scoped variables effiency in declaration

Final Edit: I'm making one last edit to this question for clarity sake. I believe it has been answered in all of the comments, but in the event there is such an option, I think it's best to clean up the question for future readers.
I recently inherited someone's Perl code and there's an interesting setup and I'm wondering if it can be made more efficient.
The program is setup to use strict and warnings (as it should). The program is setup to use global variables; meaning the variables are declared and initialized to undef at the top of the program. Specific values beyond the initial undef are then assigned to the variables throughout various loops within the program. After they are set, there is a separate report section (after all internal loops and subroutines have run) that uses the variables for its content.
There are quite a few variables and it seems repetitive to just make an initial variable declaration at the top of the program so that it is available later for output/report purposes (and to stay compliant with the strict pragma). Based on my understanding and from all of the comments received thus far, it seems this is the only way to do it, as lexically scoped variables by definition only persist in during their declared scope. So, in order to make it global it needs to be declared early (i.e. at the top).
I'm just wondering if there is a shortcut to elevate the scope of a variable to be global regardless of where it's declared, and still stay within strict's parameters of course?
My previous example was confusing, so I'll write a pseudo code example here to convey the concept (I don't have the original source with me):
# Initial declaration to create "Global variables" -- imagine about 30 or so
my ($var1, $var2, $var3); # Global
# Imagine a foreach loop going through a hash and assigning values
# to previously declared variables
for my $k (keys %h){
...
$var = 1; #$var gets set to 1 within the foreach loop
...
}
print "The final calculated report is as follows:\n";
#output $var after loop is done later in program
print "Variable 1 comes to $var1\n";
So the question: is there an acceptable shortcut that declares $var1 within the foreach loop above and escalates its scope beyond the foreach loop, so it is in effect "Global"? This would avoid the need to declare and initialize it to undef at the top of the program and still make it available for use in the program's output.
Based on feedback already received the answer seems to be an emphatic "No" due to the defined scoping constraints.
As per your own question:
So the question: is there an acceptable shortcut that declares $var1 within the foreach loop above and escalates its scope beyond the foreach loop, so it is in effect "Global"? This would avoid the need to declare and initialize it to undef at the top of the program and still make it available for use in the program's output.
You can refer to a variable name without having declared it first by using the whole name including namespace:
use strict;
use warnings;
my %h = (
first => 'value 1',
second => 'value 2',
third => 'value 3',
);
for my $k (keys %h) {
print "Processing key $k...\n";
$main::var = 1;
}
print "Variable var is now $main::var\n";
I'm assuming main as your namespace, which is the default. If your script is declaring a package, then you need to use that name. Also, if you didn't declare the variable first, you will need to use the whole package::name format everytime.
However, and just so it's clear: You don't need to "declare and initialize a variable to undef". If you do this:
my ($var1, $var2, $var3);
Those variables are already initialized to undef.
Now, you also need to understand the difference between a lexical and a global variable. Using the keyword my to declare variable at the top of your script will make them available in all the rest of your script, no matter if you are inside or outside a block. But they are not really global as they are not visible to any external module or script. If you change the keyword my to our, then they are global and visible anywhere outside that script.
I'm just wondering if there is a shortcut to elevate the scope of a variable to be global regardless of where it's declared, and still stay within strict's parameters of course?
Using global variables is dumb, but possible.
use vars qw( $foo );
It still needs to be present before any uses.

Local and Global variables in perl

I am having few doubts about the local/our scope in Perl. I read a lot of documentation, but I am still in confusion is there. Following are the confusions
What is local scope?
what I read is -> local copies the value of global variable, change the value, user will use it and outside the block it will retain the global value
Confusion -> my does the same thing. Only benefit I see is that some variables like $package::var cannot be declared with my scope but can be declared with local scope. What else for local
What is "global" variable?
What I read is -> Its scope is within the package. Basically we put the global variable in #EXPORT array and use it or append the namespace with it to use in other packages.
I doubt -> Again if we declare variable with my scope in main only then we can access the variable throughout the package. Is that right? Is it possible to add the my scoped variables in #EXPORT array and use it in another packages?
I think global variables are declared with our keyword. Is there any other way to do so?
This question may look repetitive, but I am confused.
In terms of scoping, there are three kinds of variables in Perl.
Lexical variables are lexically scoped, which means they are only visible in the current lexical scope (basically file or block).
Package variables, on the other hand, can be used using their qualified form (e.g. $Foo::x) from anywhere in the interpreter, and they can be used without qualification by any code that shares the variable's package.
Certain package variables are visible without qualification anywhere in the interpreter. These include punctuation vars and a few named vars such as #ARGV and STDOUT. For example, $x refers to $Foo::x when in package Foo and $Bar::x when in package Bar (assuming no lexical var named $x is in scope), but $_ always refers to $::_.
Variables are destroyed when they are no longer referenced.
Lexical variables are usually destroyed when the lexical scope is exited.
Package variables are usually destroyed when the program exits.
Here are ways to create variable.
my and state create a lexical variable.
our creates a lexical variable that is aliased to the variable of the same name in the current package. In other words, our $x; is equivalent to my \$x = \$Foo::x; when in package Foo.
Package variables are created on use.
local doesn't create any variables. It simply backs up a variable until the current lexical scope is destroyed. It is restored from its backed-up value at that point.
my does the same thing.
No. local does not change the scope of a variable. While a lexical variable is only visible in a lexical scope, a localized package variable is still visible across the entire interpreter.
$x = 123;
sub foo { print "$x\n"; }
{ local $x = 456; foo(); } # 456
foo(); # 123
$x = 123;
sub foo { print "$x\n"; }
{ my $x = 456; foo(); } # 123
foo(); # 123
What else for local
local is primarily used to approximate the functionality of my for variables that cannot otherwise be declared lexically.
Historically, that was all variables. Since 5.6, only punctuation variables cannot be declared lexically.
What is "global" variable?
A global variable is a variable that can seen globally.
All package variables can be seen by any code in the interpreter, so they're all global.
Or are they? To see them from other packages, you need to qualify them. Are $x and $Foo::x the same variable?
To some, global variables refers to the set of package variables you can use unqualified. It means that package changes the set of global variables. And since the package directive is usually used on a file-basis, that means file-level lexicals are also effectively global by this definition. And they are indeed called that sometimes.
But if the package changes the set of variables that are global, then they're not really global, are they? So think some people, which only consider punctuation variables (e.g. $_) and the few named variables that can be used unqualified from anywhere (*::STDOUT) to be global.
In short, it's a pretty useless term.
Is it possible to add the my scoped variables in #EXPORT array and use it in another packages?
No. #EXPORT is used by Exporter. Exporter would not be able to find anything but package symbols (since files are compiled in fresh lexical scopes), so #EXPORT must only contain package symbols.
There are two kinds of variables, lexically scoped and globally scoped.
In Perl before version 5, there was only globally scoped. These variables are the package variables. These variables are available everywhere in the program if you use the package prefix.
The local keyword was introduced to provide a way to alter the value of one of these package global variables inside a limited scope, such as inside one subroutine. It will save the old value on a stack when entering the scope with the local statement, and upon exiting, it will restore the old value. These are still package globals, which means that they are still available everywhere. If you are inside a scope with a local variable, and you call a subroutine, that variable is still visible inside that subroutine.
The my keyword was introduced in version 5, and provides lexically scoped variables. These variables only exist inside the scope where they are declared. This means that if you call a subroutine, that my variable is not visible. Upon exiting a scope, the my variables simply go away. You should prefer to use my variables when possible, because you do not want your variables to be visible inside subroutines that you call. You cannot use these type of variables in the #EXPORT list because these variables are not visible outside of their scope.
Finally, the our keyword is a combination of both, in that it gives you a variable that is a package global, but that variable is lexically scoped. This means it will be available anywhere in the program, but at the end of the enclosing block, you cannot refer to that variable any more.
Here's what I found out about variable scopes:
my declarations are pretty clear and straightforward if used inside blocks. If used in main outside any block, they are a bit different though, meaning that a my variable declared outside a block is visible even inside functions called from anywhere inside the same file as long as these functions are defined within the same file. If declared inside a block, though, they are not visible to functions even if called from the same block. All my variables seem to live on the stack. And: you cannot localize them with local.
our variables live on the heap. Even if you have a my variable by the same name, the our variable can still be accessed through ${'var'}, which looks up a variable of that name in the symbol table and dereferences it. my variables, on the other hand, have not symbol table entries.
local variables seem to me like a relic from former Perl versions. They are just re-assignments to global (our) variables with block scope and resume their former values after the block terminates. I can see no real sense in using them.
My little program below shows all this, and it shows how badly a declared() test is missing, beyond the well-known defined() test, to identify undeclared variables as such.
#!/usr/bin/perl
use strict;
### This is about variable scoping with my, our and local
my $fsv = "file scope"; # visible for all code in this file
our $gsv = "global scope"; # not different from my $fsv, except in packages
our $lsv = "global"; # global scope, but localized in subsequent block
{
my $bsv = "lex scope"; # visible only inside this block, not even in subs called from here
$gsv = "visible everywhere";
local $lsv = "global, but localized val";
print "This is variable \$bsv with value $bsv inside block\n";
print "This is variable \$fsv with value $fsv inside block\n";
print "This is variable \$lsv with value $lsv inside block\n\n";
print_vars("calledfromblock");
}
print_vars("calledfromoutside");
no strict 'vars'; # needed if testing variable for declaredness rather than definedness
if ( defined $bsv ) {
print "\$bsv as defined outside braces: $bsv\n"
} else {
print "\$bsv not defined outside braces\n";
}
print "This is variable \$lsv with value $lsv outside block\n";
# use strict 'vars'; # no strict 'vars' effective even in sub print_vars unless switched back on
sub print_vars
{
my $whence = shift;
my $gsv = "my variable";
no strict 'refs'; # needed to access the global var $gsv using ${'gsv'} despite the my declaration
if ( $whence eq "calledfromblock" ) {
print "\t print_vars called from within the block:\n";
( defined $bsv ) ? print "\$bsv is $bsv inside sub\n" : print "\$bsv not defined inside sub\n";
( defined $fsv ) ? print "\$fsv is $fsv inside sub\n" : print "\$fsv not defined inside sub\n";
( defined ${'gsv'} ) ? print "\$gsv is ${'gsv'} inside sub\n" : print "\$gsv not defined inside sub\n";
( defined ${'lsv'} ) ? print "\$lsv is ${'lsv'} inside sub\n" : print "\$lsv not defined inside sub\n";
} else {
print "\t print_vars called from outside the block:\n";
( defined $bsv ) ? print "\$bsv is $bsv inside sub\n" : print "\$bsv not defined inside sub\n";
( defined $fsv ) ? print "\$fsv is $fsv inside sub\n" : print "\$fsv not defined inside sub\n";
( defined $gsv ) ? print "\$gsv is $gsv inside sub\n" : print "\$gsv not defined inside sub\n";
( defined $lsv ) ? print "\$lsv is $lsv inside sub\n" : print "\$lsv not defined inside sub\n";
}
print "\n";
}
###Example 1:
sub mess_with_foo {
$foo=0;
}
sub myfunc {
my $foo=20;
mess_with_foo();
print $foo;
}
myfunc();
###Example 2:
sub mess_with_foo {
$foo=0;
}
sub myfunc {
local $foo=20;
mess_with_foo();
print $foo;
}
myfunc();
Example 1 prints 20 because mess_with_foo() could not see my $foo. It could not change it. my $foo can only be seen in its scope of myfunc().
Example 2 prints 0 because mess_with_foo() can see my $foo and change it. local $foo can be seen in its scope of myfunc() AND in the scope of any function called from within its scope of myfunc().
That's the only difference. Neither my $foo nor local $foo will be seen outside of their scope of myfunc().

difference between my and our ? (declared in the same file)

Before writing this program,I thought that our is a package scope variable and my is
a file scope variable.But,After did that program,I am get confused.
My program is,
#!/usr/bin/perl
use strict;
use warnings;
package one;
our $val = "sat";
my $new = "hello";
print "ONE:val =>$val \n";
print "ONE:new =>$new \n\n";
package two;
print "TWO:val =>$val \n";
print "TWO:new =>$new \n";
which outputs
ONE:val =>sat
ONE:new =>hello
TWO:val =>sat
TWO:new =>hello
So,what is the difference between my and our.Whether the both are the same or it having any difference?
As you see, both my and our have lexical effect.
my creates a lexically scoped variable.
our creates a lexically scoped alias to a package variable.
Just because you say package in no fashion changes the lexical scope, so your $val is still an alias to $one::val even after having seen the package two statement.
If you don’t see a close curly, you haven’t finished your scope. (Or EOF or end of string in a string eval).
my restrict the variables access to the innermost block in which
they were declared. If there is no block, they are file-scoped.
our instead associates a
simple name with a package variable in the current package , so it is declared at the package level and linked to the package name. our tries to help out by letting you use package variables without adding the package name.
package pack;
our $variable; # These are the same
$pack::variable; # These are the same
An our variable is something similar to C's static variable, but is different because the variable declared with our in a function is still accessible outside the function if it is called with the variable's fully qualified name.
But most of all my is lexically scoped while our is lexical scope but their life persistent even outside the declaring block(their life is like global variable life), therefore to really understand the difference between my and our you have to understand the difference between lexically and global scoped in Perl.
So briefly the difference between the two type are :
Global variables
Any code, anywhere, can change their values.
Lexical variables
The life of the variable end with the the end of the code block in with they are included, after that their values are garbage collected. These kind of variables can be accessed only within the block in which they are declared.
To answer you specific example-question : try to move the second package declaration (package two) into another file, and you will see the difference between my and our ...
It is important to distinguish between visibility and lifetime.
The visibility of variables declared using our or my is identical. You can used the name anywhere after the declaration before the first enclosing brace or end of file.
Beware that this doesn't apply to full-qualified variable names, which need no declaration and can be accessed anywhere. Without declaring anything I can assign to a package variable
$pack::three = 3;
and use that anywhere else in any package. I don't even have to declare the pack package. But if I write
package pack;
our $three;
I have generated an shortened alias for $pack::three that I can use within the same lexical scope as I could a my variable in the same place: before an enclosing brace or end of file.
These package variables are always available from the start of the program's execution. Just like hash elements you can always assign to a new one and it will always be there - their lifetime is endless. In fact package variables are hash elements to all intents and purposes.
Lexical variables, declared with my, on the other hand, are created at the point of declaration and destroyed once they go out of scope and there is no reference to them held anywhere. So, unless you take the reference of such a variable, its lifetime is the same as its visibility. A my declaration inside a loop causes a new variable to be created and destroyed for each execution the loop.
In your code, you have created an alias $val for package variable $one::val and a lexical variable $new. Neither are within a code block so both are visible to the end of the file. The package two has no effect at all here, but if you had written our $val after that second package statement you would have changed the alias $val to indicate $two::val instead.
I hope that helps.

What is the difference between my and local in Perl?

I am seeing both of them used in this script I am trying to debug and the literature is just not clear. Can someone demystify this for me?
The short answer is that my marks a variable as private in a lexical scope, and local marks a variable as private in a dynamic scope.
It's easier to understand my, since that creates a local variable in the usual sense. There is a new variable created and it's accessible only within the enclosing lexical block, which is usually marked by curly braces. There are some exceptions to the curly-brace rule, such as:
foreach my $x (#foo) { print "$x\n"; }
But that's just Perl doing what you mean. Normally you have something like this:
sub Foo {
my $x = shift;
print "$x\n";
}
In that case, $x is private to the subroutine and its scope is enclosed by the curly braces. The thing to note, and this is the contrast to local, is that the scope of a my variable is defined with respect to your code as it is written in the file. It's a compile-time phenomenon.
To understand local, you need to think in terms of the calling stack of your program as it is running. When a variable is local, it is redefined from the point at which the local statement executes for everything below that on the stack, until you return back up the stack to the caller of the block containing the local.
This can be confusing at first, so consider the following example.
sub foo { print "$x\n"; }
sub bar { local $x; $x = 2; foo(); }
$x = 1;
foo(); # prints '1'
bar(); # prints '2' because $x was localed in bar
foo(); # prints '1' again because local from foo is no longer in effect
When foo is called the first time, it sees the global value of $x which is 1. When bar is called and local $x runs, that redefines the global $x on the stack. Now when foo is called from bar, it sees the new value of 2 for $x. So far that isn't very special, because the same thing would have happened without the call to local. The magic is that when bar returns we exit the dynamic scope created by local $x and the previous global $x comes back into scope. So for the final call of foo, $x is 1.
You will almost always want to use my, since that gives you the local variable you're looking for. Once in a blue moon, local is really handy to do cool things.
Dynamic Scoping. It is a neat concept. Many people don't use it, or understand it.
Basically think of my as creating and anchoring a variable to one block of {}, A.K.A. scope.
my $foo if (true); # $foo lives and dies within the if statement.
So a my variable is what you are used to. whereas with dynamic scoping $var can be declared anywhere and used anywhere.
So with local you basically suspend the use of that global variable, and use a "local value" to work with it. So local creates a temporary scope for a temporary variable.
$var = 4;
print $var, "\n";
&hello;
print $var, "\n";
# subroutines
sub hello {
local $var = 10;
print $var, "\n";
&gogo; # calling subroutine gogo
print $var, "\n";
}
sub gogo {
$var ++;
}
This should print:
4
10
11
4
Quoting from Learning Perl:
But local is misnamed, or at least misleadingly named. Our friend Chip Salzenberg says that if he ever gets a chance to go back in a time machine to 1986 and give Larry one piece of advice, he'd tell Larry to call local by the name "save" instead.[14] That's because local actually will save the given global variable's value away, so it will later automatically be restored to the global variable. (That's right: these so-called "local" variables are actually globals!) This save-and-restore mechanism is the same one we've already seen twice now, in the control variable of a foreach loop, and in the #_ array of subroutine parameters.
So, local saves a global variable's current value and then set it to some form of empty value. You'll often see it used to slurp an entire file, rather than leading just a line:
my $file_content;
{
local $/;
open IN, "foo.txt";
$file_content = <IN>;
}
Calling local $/ sets the input record separator (the value that Perl stops reading a "line" at) to an empty value, causing the spaceship operator to read the entire file, so it never hits the input record separator.
I can’t believe no one has linked to Mark Jason Dominus’ exhaustive treatises on the matter:
Coping with Scoping
And afterwards, if you want to know what local is good for after all,Seven Useful Uses of local
http://perldoc.perl.org/perlsub.html#Private-Variables-via-my()
Unlike dynamic variables created by
the local operator, lexical variables
declared with my are totally hidden
from the outside world, including any
called subroutines. This is true if
it's the same subroutine called from
itself or elsewhere--every call gets
its own copy.
http://perldoc.perl.org/perlsub.html#Temporary-Values-via-local()
A local modifies its listed variables
to be "local" to the enclosing block,
eval, or do FILE --and to any
subroutine called from within that
block. A local just gives temporary
values to global (meaning package)
variables. It does not create a local
variable. This is known as dynamic
scoping. Lexical scoping is done with
my, which works more like C's auto
declarations.
I don't think this is at all unclear, other than to say that by "local to the enclosing block", what it means is that the original value is restored when the block is exited.
Well Google really works for you on this one: http://www.perlmonks.org/?node_id=94007
From the link:
Quick summary: 'my' creates a new
variable, 'local' temporarily amends
the value of a variable.
ie, 'local' temporarily changes the
value of the variable, but only
within the scope it exists in.
Generally use my, it's faster and doesn't do anything kind of weird.
From man perlsub:
Unlike dynamic variables created by the local operator, lexical variables declared with my are totally hidden from the outside world, including any called subroutines.
So, oversimplifying, my makes your variable visible only where it's declared. local makes it visible down the call stack too. You will usually want to use my instead of local.
Your confusion is understandable. Lexical scoping is fairly easy to understand but dynamic scoping is an unusual concept. The situation is made worse by the names my and local being somewhat inaccurate (or at least unintuitive) for historical reasons.
my declares a lexical variable -- one that is visible from the point of declaration until the end of the enclosing block (or file). It is completely independent from any other variables with the same name in the rest of the program. It is private to that block.
local, on the other hand, declares a temporary change to the value of a global variable. The change ends at the end of the enclosing scope, but the variable -- being global -- is visible anywhere in the program.
As a rule of thumb, use my to declare your own variables and local to control the impact of changes to Perl's built-in variables.
For a more thorough description see Mark Jason Dominus' article Coping with Scoping.
local is an older method of localization, from the times when Perl had only dynamic scoping. Lexical scoping is much more natural for the programmer and much safer in many situations. my variables belong to the scope (block, package, or file) in which they are declared.
local variables instead actually belong to a global namespace. If you refer to a variable $x with local, you are actually referring to $main::x, which is a global variable. Contrary to what it's name implies, all local does is push a new value onto a stack of values for $main::x until the end of this block, at which time the old value will be restored. That's a useful feature in and of itself, but it's not a good way to have local variables for a host of reasons (think what happens when you have threads! and think what happens when you call a routine that genuinely wants to use a global that you have localized!). However, it was the only way to have variables that looked like local variables back in the bad old days before Perl 5. We're still stuck with it.
"my" variables are visible in the current code block only. "local" variables are also visible where ever they were visible before. For example, if you say "my $x;" and call a sub-function, it cannot see that variable $x. But if you say "local $/;" (to null out the value of the record separator) then you change the way reading from files works in any functions you call.
In practice, you almost always want "my", not "local".
Look at the following code and its output to understand the difference.
our $name = "Abhishek";
sub sub1
{
print "\nName = $name\n";
local $name = "Abhijeet";
&sub2;
&sub3;
}
sub sub2
{
print "\nName = $name\n";
}
sub sub3
{
my $name = "Abhinav";
print "\nName = $name\n";
}
&sub1;
Output is :
Name = Abhishek
Name = Abhijeet
Name = Abhinav
&s;
sub s()
{
local $s="5";
&b;
print $s;
}
sub b()
{
$s++;
}
The above script prints 6.
But if we change local to my it will print 5.
This is the difference. Simple.
It will differ only when you have a subroutine called within a subroutine, for example:
sub foo {
print "$x\n";
}
sub bar { my $x; $x = 2; foo(); }
bar();
It prints nothing as $x is limited by {} of bar and not visible to called subroutines, for example:
sub foo { print "$x\n"; }
sub bar { local $x; $x = 2; foo(); }
bar();
It will print 2 as local variables are visible to called subroutines.
dinomite's example of using local to redefine the record delimiter is the only time I have ran across in a lot of perl programming. I live in a niche perl environment [security programming], but it really is a rarely used scope in my experience.
I think the easiest way to remember it is this way. MY creates a new variable. LOCAL temporarily changes the value of an existing variable.
#!/usr/bin/perl
sub foo { print ", x is $x\n"; }
sub testdefault { $x++; foo(); } # prints 2
sub testmy { my $x; $x++; foo(); } # prints 1
sub testlocal { local $x = 2; foo(); } # prints 2. new set mandatory
print "Default, everything is global";
$x = 1;
testdefault();
print "My does not affect function calls outside";
$x = 1;
testmy();
print "local is everything after this but initializes a new";
$x = 1;
testlocal();
As mentioned in testlocal comment, declaring "local $x;" means that $x is now undef