Lexical Scoping
The new my() operator enables you to declare variables that are truly lexically scoped. Previously, the closest you could get to a lexical variable was with local(). The my() variables are visible only within the current block (within a set of curly braces) and go out of scope immediately after exiting the block. The following example illustrates their use:
$foo = "I\'m foo in a global context\n";
print $foo;
{ # the curlies open a new lexical context (block)
my $foo = "But I\'m bar in this short lexical context\n";
print $foo;
} # lexically scoped $foo goes out of scope here
print $foo;
# prints:
I'm foo in a global context
But I'm bar in this short lexical context
I'm foo in a global context
The my() variable is used extensively in the modules that you'll explore in this book. See PERLVAR for complete details on all types of Perl variables, including lexical variables.