This is a code lifted straight from Perl Cookbook:
#colors = qw(red blue green yellow orange purple violet);
for my $name (#colors) {
no strict 'refs';
*$name = sub { "<FONT COLOR='$name'>#_</FONT>" };
}
It's intention is to form 6 different subroutines with names of different colors. In the explanation part, the book reads:
These functions all seem independent, but the real code was in fact only compiled once. This technique
saves on both compile time and memory use. To create a proper closure, any variables in the anonymous
subroutine must be lexicals. That's the reason for the my on the loop iteration variable.
What is meant by proper closure, and what will happen if the my is omitted? Plus how come a typeglob is working with a lexical variable, even though typeglobs cannot be defined for lexical variables and should throw error?
As others have mentioned the cookbook is using the term "proper" to refer to the fact that a subroutine is created that carries with it a variable that is from a higher lexical scope and that this variable can no longer be reached by any other means. I use the over simplified mnemonic "Access to the $color variable is 'closed'" to remember this part of closures.
The statement "typeglobs cannot be defined for lexical variables" misunderstands a few key points about typeglobs. It is somewhat true it you read it as "you cannot use 'my' to create a typeglob". Consider the following:
my *red = sub { 'this is red' };
This will die with "syntax error near "my *red" because its trying to define a typeglob using the "my" keyword.
However, the code from your example is not trying to do this. It is defining a typeglob which is global unless overridden. It is using the value of a lexical variable to define the name of the typeglob.
Incidentally a typeglob can be lexically local. Consider the following:
my $color = 'red';
# create sub with the name "main::$color". Specifically "main:red"
*$color = sub { $color };
# preserve the sub we just created by storing a hard reference to it.
my $global_sub = \&$color;
{
# create a lexically local sub with the name "main::$color".
# this overrides "main::red" until this block ends
local *$color = sub { "local $color" };
# use our local version via a symbolic reference.
# perl uses the value of the variable to find a
# subroutine by name ("red") and executes it
print &$color(), "\n";
# use the global version in this scope via hard reference.
# perl executes the value of the variable which is a CODE
# reference.
print &$global_sub(), "\n";
# at the end of this block "main::red" goes back to being what
# it was before we overrode it.
}
# use the global version by symbolic reference
print &$color(), "\n";
This is legal and the output will be
local red
red
red
Under warnings this will complain "Subroutine main::red redefined"
I believe that "proper closure" just means actually a closure. If $name is not a lexical, all the subs will refer to the same variable (whose value will have been reset to whatever value it had before the for loop, if any).
*$name is using the value of $name as the reference for the funny kind of dereferencing a * sigil does. Since $name is a string, it is a symbolic reference (hence the no strict 'refs').
From perlfaq7:
What's a closure?
Closures are documented in perlref.
Closure is a computer science term with a precise but hard-to-explain
meaning. Usually, closures are implemented in Perl as anonymous
subroutines with lasting references to lexical variables outside their
own scopes. These lexicals magically refer to the variables that were
around when the subroutine was defined (deep binding).
Closures are most often used in programming languages where you can
have the return value of a function be itself a function, as you can
in Perl. Note that some languages provide anonymous functions but are
not capable of providing proper closures: the Python language, for
example. For more information on closures, check out any textbook on
functional programming. Scheme is a language that not only supports
but encourages closures.
The answer carries on to answer the question in some considerable detail.
The Perl FAQs are a great resource. But it's a bit of a waste of effort maintaining them if no-one ever reads them.
Edit (to better answer the later questions in your post):
1/ What is meant by proper closure? - see above
2/ What will happen if the my is omitted? - It won't work. Try it and see what happens.
3/ How come a typeglob is working with a lexical variable? - The variable $name is only being used to define the name of the typeglob to work with. It's not actually being used as a typeglob.
Does that help more?
Related
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.
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.
{
sub a {
print 1;
}
}
a;
A bug,is it?
a should not be available from outside.
Does it work in Perl 6*?
* Sorry I don't have installed it yet.
Are you asking why the sub is visible outside the block? If so then its because the compile time sub keyword puts the sub in the main namespace (unless you use the package keyword to create a new namespace). You can try something like
{
my $a = sub {
print 1;
};
$a->(); # works
}
$a->(); # fails
In this case the sub keyword is not creating a sub and putting it in the main namespace, but instead creating an anonymous subroutine and storing it in the lexically scoped variable. When the variable goes out of scope, it is no longer available (usually).
To read more check out perldoc perlsub
Also, did you know that you can inspect the way the Perl parser sees your code? Run perl with the flag -MO=Deparse as in perl -MO=Deparse yourscript.pl. Your original code parses as:
sub a {
print 1;
}
{;};
a ;
The sub is compiled first, then a block is run with no code in it, then a is called.
For my example in Perl 6 see: Success, Failure. Note that in Perl 6, dereference is . not ->.
Edit: I have added another answer about new experimental support for lexical subroutines expected for Perl 5.18.
In Perl 6, subs are indeed lexically scoped, which is why the code throws an error (as several people have pointed out already).
This has several interesting implications:
nested named subs work as proper closures (see also: the "will not stay shared" warning in perl 5)
importing of subs from modules works into lexical scopes
built-in functions are provided in an outer lexical scope (the "setting") around the program, so overriding is as easy as declaring or importing a function of the same name
since lexpads are immutable at run time, the compiler can detect calls to unknown routines at compile time (niecza does that already, Rakudo only in the "optimizer" branch).
Subroutines are package scoped, not block scoped.
#!/usr/bin/perl
use strict;
use warnings;
package A;
sub a {
print 1, "\n";
}
a();
1;
package B;
sub a {
print 2, "\n";
}
a();
1;
Named subroutines in Perl are created as global names. Other answers have shown how to create a lexical subroutines by assigning an anonymous sub to a lexical variable. Another option is to use a local variable to create a dynamically scoped sub.
The primary differences between the two are call style and visibility. The dynamically scoped sub can be called like a named sub, and it will also be globally visible until the block it is defined in is left.
use strict;
use warnings;
sub test_sub {
print "in test_sub\n";
temp_sub();
}
{
local *temp_sub = sub {
print "in temp_sub\n";
};
temp_sub();
test_sub();
}
test_sub();
This should print
in temp_sub
in test_sub
in temp_sub
in test_sub
Undefined subroutine &main::temp_sub called at ...
At the risk of another scolding by #tchrist, I am adding another answer for completeness. The as yet to be released Perl 5.18 is expected to include lexical subroutines as an experimental feature.
Here is a link to the relevant documentation. Again, this is very experimental, it should not be used for production code for two reasons:
It might not be well implemented yet
It might be removed without notice
So play with this new toy if you want, but you have been warned!
If you see the code compile, run and print "1", then you are not experiencing a bug.
You seem to be expecting subroutines to only be callable inside the lexical scope in which they are defined. That would be bad, because that would mean that one wouldn't be able to call subroutines defined in other files. Maybe you didn't realise that each file is evaluated in its own lexical scope? That allows the likes of
my $x = ...;
sub f { $x }
Yes, I think it is a design flaw - more specifically, the initial choice of using dynamic scoping rather than lexical scoping made in Perl, which naturally leads to this behavior. But not all language designers and users would agree. So the question you ask doesn't have a clear answer.
Lexical scoping was added in Perl 5, but as an optional feature, you always need to indicate it specifically. With that design choice I fully agree: backward compatibility is important.
Why does this print 42:
$answer = 42;
$variable = "answer";
print ${$variable} . "\n";
but this doesn't:
my $answer = 42;
my $variable = "answer";
print ${$variable} . "\n";
Only package variables (the kind declared in your first example) can be targeted via symbolic references. Lexical (my) variables, cannot be, which is why your second example fails.
See the excellent article Coping with Scoping for how the two separate variable systems in Perl operate. And see the also excellent Why it's stupid to use a variable variable name for why that's stupid. :)
Perl has two entirely separate but largely compatible variable systems, package variables, as in your first example, and lexical variables, as in the second. There are a few things that each can do but the other cant:
Package variables are the only ones that can be:
localized (with local)
used as the target for a symbolic reference (the reason the OP's second example doesnt work)
used as barewords (sub definitions, file handles)
used with typeglobs (because that's what the symbol really is under the hood)
Lexical variables are the only ones that can be closed over (used in a lexical closure).
Using strict would help by forcing you to declare package variables with our, making the difference clearer.
There are several times where symbolic references are useful in Perl, most center around manipulating the symbol table (like writing your own import in a module rather than using Exporter, monkey-patching modules at runtime, various other meta-programming tasks). All of these are advanced topics.
For other tasks, there is usually a better way to do it such as with a hash. The general rule of thumb is to always run under use warnings; use strict; unless you know there isn't any other way but to disable a portion of the pragma (such as using no strict 'refs'; in as small a scope as possible).
Symbolic references only work with package variables. The symbol table doesn't track lexical variables (which is the entire point of them being lexical :).
The problem is that you can't use a symbolic reference to refer to a lexical variable. In both examples ${$variable} is looking for $main::answer. In the first, $answer is a package global and short for $main::answer, so the reference finds it. In the second, $answer is a lexical variable and doesn't live in any package, so the reference can't find it.
More details in perlref under heading Symbolic references.
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