I thought that I would no longer be able to call $cfg once inside the 'unless'
You seem to have figured this out, but I'd just like to reinforce the point. Scalar variables are accessible from inner scopes, but not from outer scopes. So if you scope a variable in the top-level of a subroutine, then any nested blocks (if statements, while loops, etc) will have access to the variable. But anything outside of the subroutine will not. Here's the obligatory code example:
sub foo {
my $foo = 1;
if (1 == 1) { # just to demonstrate the point
$foo++; # inside foo, works fine
}
print $foo;
bar();
}
sub bar {
print $foo; # outside foo, blows up
}
foo();
Also keep in mind that the inner/outer determination is done "physically". That is, it's not based on the call stack. It's based on the location in the actual code. This is different from dynamic scoping (i.e. local in Perl), which is based on the execution path. For this reason, lexical scoping is much more predictable and understandable. Here's an example:
sub foo {
local $foo = 1;
if (1 == 1) { # just to demonstrate the point
$foo++;
}
print "From foo: $foo\n";
bar();
}
sub bar {
# this variable will be set to whatever it was
# before we got called
print "From bar: $foo\n";
}
$foo = 5;
foo();
bar();
|