This week, Perl 101 introduces you to subroutines and teaches youhow to structure your code for maximum reusability. Also included: returnvalues, my() and local() constructs, and a marriage proposal.
So Perl gives you "public" variables and "private" variables - more than enough for most programmers. But you know what geeks are like...they're never satisfied. And so Perl also provides a useful middle ground - variables which are available between subroutines, but are hidden from the main program.
Why would you want to use something like this? Well, consider the following example, which demonstrates the concept:
#!/usr/bin/perl
# define some subroutines
sub display_value
{
print "During the subroutine...you are $age years old.\n";
}
sub change_age
{
local ($age) = $age + $increment;
&display_value($age);
}
# ask for age
print "How old are you?\n";
$age = ;
chomp ($age);
# ask for increment
print "How many years would you like to add?\n";
$increment = ;
chomp ($increment);
# demonstrate local variable
print "Before invoking the subroutine...you are $age years old.\n";
&change_age;
print "After invoking the subroutine...you are $age years old.\n";
And here's what it looks like:
How old are you?
32
How many years would you like to add?
9
Before invoking the subroutine...you are 32 years old.
During the subroutine...you are 41 years old.
After invoking the subroutine...you are 32 years old.When making calls between subroutines in this manner, it
often becomes necessary to store the value of a variable across subroutines - and that's where local() comes in. In the example above, the variable $age is assigned an initial [global] value on the basis of user input. However, once the &change_age subroutine is invoked, this global value is stored and a new value is assigned to $age.
So far so good...we've already seen this with my(). But now, &change_age needs to call &display_value, and pass it the value of the variable $age. By declaring $age to be a "local" variable, Perl makes it possible for the &display_value subroutine to access the new value of $age, and display it.
Once the subroutines finish and return control to the main program, the original value of $age is restored, and displayed. Thus, the example demonstrates how the local() keyword can be used to share variable values between subroutines, without affecting the global value of the variable.
And that's about it for this week. Next time, we'll be taking a close look at some of Perl's built-in string, math and pattern-recognition functions...so make sure you come back!
This article copyright Melonfire 2000. All rights reserved.