Perl 101 (Part 5) - Sub-Zero Code - My() Hero! (
Page 6 of 7 )
Let's now talk
a little bit about the variables used within a subroutine, and their
relationship with variables in the main program. Unless you specify otherwise,
the variables used within a subroutine are global - that is, the values assigned
to them are available throughout the program, and changes made to them during
subroutine execution are not restricted to the subroutine space
alone.
For a clearer example of what this means, consider this simple
example:
#!/usr/bin/perl
# define a subroutine
sub change_value
{
$hero = "Wolverine";
}
# define a variable
$hero = "The Incredible Hulk";
# before invoking subroutine
print "Today's superhero is $hero\n";
print "Actually, I've changed my mind...";
&change_value;
# after invoking subroutine
print "...gimme $hero instead.\n";
And here's what you'll see:
Today's superhero is The Incredible Hulk
Actually, I've changed my mind......gimme Wolverine instead.
Obviously, this is not always what you want - there are
numerous situations where you'd prefer the variables within a subroutine to
remain "private", and not disturb the variables within the main program. And
this is precisely the reason for Perl's my() construct.
The my()
construct allows you to define variables whose influence does not extend outside
the scope of the subroutine within which they are enclosed. Take a look:
#!/usr/bin/perl
# define a subroutine
sub change_value
{
# this statement added
my ($hero);
$hero = "Wolverine";
}
# define a variable
$hero = "The Incredible Hulk";
# before invoking subroutine
print "Today's superhero is $hero\n";
print "Actually, I've changed my mind...";
&change_value;
# after invoking subroutine
print "...gimme $hero instead.\n";
And here's what you'll get:
Today's superhero is The Incredible Hulk
Actually, I've changed my mind......gimme The Incredible Hulk instead.
What happens here? Well, when you define a variable with the
"my" keyword, Perl first checks to see if a variable already exists with the
same name. If it does [as in the example above], its value is stored and a new
variable is created for the duration of the subroutine. Once the subroutine has
completed its task, this new variable is destroyed and the previous value of the
variable is restored.
The my() operator can be used with both scalar and
array variables. And - since Perl is all about efficiency - you can assign a
value to the variable at the same that that you declare it, like this:
sub change_value
{
my ($hero) = "Wolverine";
}
This article copyright Melonfire
2000. All rights reserved.