my variables are statically bound.
sub test_a { my $var = "Hello World\n"; } sub test_b { print($var); # XXX Doesn't print Hello World. } test_a(); print($var); # Doesn't print Hello World.
local variables are dynamically bound.
sub test_a { local $var = "Hello World\n"; } sub test_b { print($var); # Prints Hello World. } test_a(); print($var); # Doesn't print Hello World.
However, dynamic binding is rarely used, because its use leads to fragile software. In Perl, local is mostly used to assign a new value to a builtin global, while automatically restoring the global's value when the block is exited.
sub test { $_ = $_[0]; s/([a-z])/uc($1)/eg; return $_; } foreach (qw(a b c)) { print(test($_), "\n"); } $ perl script.pl Modification of a read-only value attempted at script.pl line 3.
It's trying to modify the constant 'a', since $_ is a reference to it. Fix:
sub test { local $_ = $_[0]; s/([a-z])/uc($1)/eg; return $_; } foreach (qw(a b c)) { print(test($_), "\n"); } $ perl script.pl A B C
In reply to Re: Difference my and local
by ikegami
in thread Difference my and local
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |