local our $bob = 'bob';is a program, if it should ever be used.
$bob = "billy";
{
local our $bob = "bob";
print $bob; # prints "bob", hides the $bob from outside the block
};
print $bob; # actually prints "billy", because the local scope is gone
our $bob; local $bob; $bob = 'bob';
our $bob; disables use strict 'vars' for $bob for the remainder of current scope. It allows you to use package variable $bob without its package name where you might have had to without our $bob;.
local $bob; saves the current value of $bob (and sets $bob for the remainder of the current scope. When the scope is exited (whether normally or by exception), $bob reclaims the value saved by local $bob.
$bob = 'bob'; assigns a value to $bob.
Now, let's put these into context.
Say you wish to take advantage of dynamic scoping. That means you need to use a package variable, not a lexical (my) variable. To avoid having to specify the package name when using that package variable, you use our. Let's also say you wish to protect the value that's currently being held by this variable. local would be used. What follows is an example of this:
use strict;
use warnings;
package MyModule;
sub do_it {
my ($arg) = @_;
our $VERBOSE;
...
warn(...)
if $VERBOSE;
...
}
sub do_it_quietly {
my ($arg) = @_;
our $VERBOSE; # Avoid saying $MyModule::VERBOSE
local $VERBOSE; # Save existing value.
$VERBOSE = 0; # Disable logging.
do_it($arg);
}
1;
our $bob; disables use strict 'vars' for $bob for the remainder of current scope.For my interest, is that actually how our is implemented, or is that just your way of explaining the effect?
I'm not an internals guy, but I think loosely speaking what the compiler does is create a glob entry for that variable name in the current package's symbol table. This way, even when strict is in effect, the compiler can verify that that variable name, used unqualified, is valid because that name exists in the symbol table (after it checks that there's no lexical with that name in the pad).
Actually it has to do a little more than that, because the scope of the our declaration is lexical; that is, you can do this:
package A; our $foo; package B; print $foo;and it will still be referring to $A::foo. Not sure how it handles that.
perlmonks.org content © perlmonks.org and Anonymous Monk, aufflick, codeacrobat, Errto, gam3, ikegami
prlmnks.org © 2006 edmund von der burg (eccles & toad)
v 0.03