In this fifth part to a six-part article series on subroutines and functions in Perl, you'll learn about lexical variables, and how passing arguments works. This article was excerpted from chapter six of the book Beginning Perl, Second Edition, written by James Lee (Apress; ISBN: 159059391X).
The range of effect that a variable has is called its scope, and lexical variables declared with my()are said to have lexical scope. This is also known as local scope. That is, they exist from the point where they’re declared until the end of the enclosing block. The name “lexical” comes from the fact that they’re confined to a well-defined chunk of text.
my $x; $x = 30; { my $x; # New $x $x = 50; # We can’t see the old $x, even if we want to. } print $x; # This $x is, and always has been, 30.
Great. We can now use variables in our subroutines in the knowledge that we’re not going to upset any behavior outside them. Let’s modifyglobal2.plby addingmy()in the function (now calledchange_global_not()):