in reply to About (my, local, ours) declaring variables
There's really no relation between those functions, and my is the only one which declares variables. In short,
my creates a lexically scoped variable. That means it only exists within the current block/file. For example,
{ my $var; } # $var no longer exists.
our is the same as no strict 'vars';, except is only affects the specified (package) var or vars. Like use strict, its effect is bound to the current block/file. For example,
package main; use strict; $main::var = 1; #$var = 1; # Error! { $main::var++; #$var++; # Error! our $var; # Disable "strict vars" for $var. $var++; # Same as "$main::var++;" } # "strict vars" is back on for $var. { $main::var++; #$var++; # Error! no strict 'vars'; # Disable "strict vars" for all vars. $var++; # Same as "$main::var++;" } # "strict vars" is back on for all vars. print("$main::var\n"); # Prints 5. #print("$var\n"); # Error!
local saves the current value of a package variable, and restores it when the current block is exited, even if it is exited by exception. For example,
$main::var = 1; { local $main::var; # Saves current value of $main::var # and sets new value to undef. $main::var = 2; } # Restores saved value of $main::var. print("$main::var\n"); # Prints 1.
which is the same as
package main; our $var; $var = 1; { local $var; # Saves current value of $main::var # and sets new value to undef. $var = 2; } # Restores saved value of $main::var. print("$var\n"); # Prints 1.
Now, you're probably wondering when to use lexical variables and when to use package variables.
Again in short, you want to use lexicals whenever possible. There are a few situations that mandate using pacakge variables:
Package variables are used for global variables which need to be accessed from other modules. For example, @ISA and @EXPORT are package variables.
Package variables are also used when dynamic scoping is needed, because of local makes it easy to do so. For example,
sub recursive { our $state; ... if (...) { local $state = ~~~; recursive(); } ... }
Package variables are needed for (?{ ... }) and similar constructs in regexps.
Aliases are created using package variables (except when using some modules). For example,
my $var = 1; our $alias; *alias = \$var; $alias = 2; print("$var\n"); # 2
The variables in perlvar are package variables, so you can use local on them.
|
|---|