$var = 42;
dosomething($var);
sub dosomething {
local ($var) = @_;
&dosomethingelse;
print "\$var is now $var\n";
}
sub dosomethingelse {
$var++;
}
Using local, you will print 43. If you change local to my, you will get
42.
local makes a variable visible to all subroutines called from the scope
where the variable was 'local' ized. 'my' does not behave like that.
I don't seem to be able to "localize" any lexical variables with 'use
strict' (if i remove 'use strict', it works fine)
1 #!/usr/bin/perl -w
2 use strict;
3 use diagnostics;
4
5 my $var = 42;
6
7 dosomething($var);
8
9 sub dosomething {
10 local ($var) = @_;
11 &dosomethingelse;
12 print "\$var is now $var\n";
13 }
14
15 sub dosomethingelse {
16 $var++;
17 }
~
Output:
:!./cccc
Can't localize lexical variable $var at ./cccc line 10 (#1)
(F) You used local on a variable name that was previously declared
as a
lexical variable using "my". This is not allowed. If you want to
localize a package variable of the same name, qualify it with the
package name.
Uncaught exception from user code:
Can't localize lexical variable $var at ./cccc line 10.
../cccc: exited with status 255
Press any key to continue [: to enter more ex commands]: