4.7.1. The Difference Between local and my
But what if the subroutine called another subroutine, one that
did notice that the variable was being borrowed
by local? For example:
$office = "global"; # Global $office
&say( ); # says "global", accessing $office directly
&fred( ); # says "fred", dynamic scope,
# because fred's local $office hides the global
&barney( ); # says "global", lexical scope;
# barney's $office is visible only in that block
sub say { print "$office\n"; } # print the currently visible $office
sub fred { local($office) = "fred"; &say( ); }
sub barney { my($office) = "barney"; &say( ); }
First, we call the subroutine &say, which
tells us which $office it sees -- the global
$office. That's normal.
But then we call Fred's subroutine. Fred has made his own
local $office, so he has actually changed the
behavior of the &say subroutine; now it tells
us what's in Fred's $office. We
can't tell whether that's what Fred wanted to do or not
without understanding the meaning of his code. But it's a
little odd.
Barney, however, is a little smarter, as well as being shorter, so he
uses the shorter (and smarter) operator, my.
Barney's variable $office is private, and
Barney's private $office can't be
accessed from outside his subroutine, so the
&say subroutine is back to normal; it can see
only the global $office. Barney didn't
change the way &say works, which is more like
what most programmers would want and expect.