Unless you declare a variable with my
, variables without a full package specification go into the current package. Here's how you might see variables used for the first time and what they would be:
my $temp; # a scoped, lexical variable that does not live in any package
state $temp; # a persistent lexical variable
our $temp; # a package variable in the current package, declared
$temp; # a package variable in the current package
$main::temp # a package variable in main
$Foo::Bar::temp # a package variable in Foo::Bar
local $temp # a package variable in the current package, with a dynamically-scoped (temporary) value
The local
sets the scope of a package variable. When you declare this "dynamic" scope, Perl uses the temporary value you set until the end of the scope. As with other package variables, Perl creates them when you first use them. That you might use it first with local
in front doesn't affect that.
Many people who tried to answer your question immediately nagged you about strict
. This is a programming aid that helps you not mistype a variable name by forcing you to declare all variables you intend to use. When you use a variable name you haven't declared, it stops the compilation of your program. You can do that with the vars
pragma, my
, state
, or our
:
use vars qw($temp);
our $temp;
my $temp;
state $temp;
local
isn't part of that, as you've seen. Why? Because that's just how it is. I'd like it more if it were different.
strict
won't complain if you use the full package specification, such as $Foo::Bar::temp
. You can mistype all of those without ever noticing.
I mostly reserve my use of local
for Perl's special variables, which you don't have to declare. If I want to use $_
in a subroutine, perhaps to use the operators that use $_
by default, I'll probably start that with local $_
:
sub something {
local $_ = shift @_;
s/.../.../;
tr/.../.../;
...;
}
I probably use local
more often with the input record separator so I can use different line endings without affecting might have come before:
my $data = do { local $/; <FILE> };
Those work because there's an implicit first use of those variables that you haven't seen.
Otherwise, I probably want to make variables private to its subroutine so nothing outside the subroutine can see it. In that case, I don't want a package variable that the rest of the program can read or write. That's the job for my
variables:
sub something {
my $temp = ...;
}
The trick of programming is to limit what can happen to exactly what you want. If the rest of your program shouldn't be able to see or change the variable, my
is the way to go.
I explain this is Learning Perl and write about the details of the package variables in Mastering Perl.