perldoc -f my Quote:
A "my" declares the listed variables to be local (lexically) to
the enclosing block, file, or "eval".
If you wanted to declare the variable in one subroutine and use it in another, you will be using an undefined variable (with a fatal error if strict is used). If you want only subroutines foo and bar to have access to the variable, you can put those subroutines together in the same scope with the variable declaration (either in the same file or like this)
Code:
{
my $baz = "threads";
sub foo {
$bar = "gossamer-";
print $bob;
}
sub bar {
$bar = "threads";
print $bob;
}
}
foo; # prints "gossamer-"
bar; # prints "threads"
print $baz; # without strict vars, prints undef
# with strict vars, 'Global symbol "$baz" requires explicit package name at'
Or if you aren't so concerned about only a couple subroutines using the variable, just declare the variable at the top of a file and never redefine it (and only use it within that file). Here are some alternatives
set the variable as needed from the stack
Code:
{
my $xyz;
sub xyz (;$) {
if (@_) {
$xyz = shift;
} else {
return $xyz;
}
}
}
xyz ("gossamer-");
print xyz; # if you use &xyz and @_ is defined, you get a different meaning
xyz ("threads");
print xyz;
# "gossamer-threads"
make the subroutine return an lvalue
Code:
{
my $xyz;
sub xyz : lvalue {
$xyz;
}
}
xyz = "gossamer-";
xyz .= "threads";
print xyz;
# gossamer-threads
use a private subroutine (as close as perl can come)
Code:
sub foo {
my $baz = "gossamer-";
local *bar = sub {
$baz .= "threads";
};
&bar;
print $baz;
}
foo; # gossamer-threads
use a package variable (note: this is what happens if you don't use "our", "use vars", or "my" and you don't use "strict vars")
Code:
our $baz; # tells perl we will be using "$baz" when we mean "$main::baz"
sub foo {
$baz = "gossamer-";
print $baz;
}
sub bar {
$baz = "threads";
print $baz;
}
foo;
bar; # gossamer-threads
print "\n";
bar;
foo; # threadsgossamer-