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.
Usually, when a subroutine is invoked in Perl, it generates a "return value". This return value is either the value of the last expression evaluated within the subroutine, or a value explicitly returned via the "return" statement. We'll examine both these a little further down - but first, here's a quick example of how a return value works.
#!/usr/bin/perl
# define a subroutine
sub change_temp
{
$celsius = 35;
$fahrenheit = ($celsius * 1.8) + 32;
}
# assign return value to variable
$result = &change_temp;
print "35 Celsius is $result Fahrenheit\n";
In this case, the value of the last expression evaluated
within the subroutine serves as its return value - this value is then assigned to the variable $result when the subroutine is invoked from within the program.
Of course, it's also possible to explicitly specify a return value - use the "return" statement, as we've done in the next example:
#!/usr/bin/perl
# define a subroutine
sub do_you
{
if ($tall == 1 && $dark == 1 && $handsome == 1)
{
return "Yes!\n";
}
else
{
return "Nope, afraid I don't feel the same way about you!\n";
}
}
$tall = 1;
$dark = 1;
$handsome = 1;
# pop the question
print "Will you marry me?\n";
# assign return value to variable
$answer = &do_you;
# print the answer
print $answer;
This article copyright Melonfire 2000. All rights reserved.{mospagebreak title=Jumping Cows And Extra-Large Pumpkins} Return values from a subroutine can even be substituted for variables anywhere in a program. For example, you could modify the last two lines of the example above to read:
#!/usr/bin/perl
# define a subroutine
sub do_you
{
if ($tall == 1 && $dark == 1 && $handsome == 1)
{
return "Yes!\n";
}
else
{
return "Nope, afraid I don't feel the same way about you!\n";
}
}
$tall = 1;
$dark = 1;
$handsome = 1;
# pop the question
print "Will you marry me?\n";
# assign return value to variable and print
print(&do_you);
And, of course, return values need not be scalar variables
alone - a subroutine can just as easily return an array variable, as we've demonstrated in the following example:
#!/usr/bin/perl
# define a subroutine
sub split_me
{
split(" ", $string);
}
# define string
$string = "The cow jumped over the moon and turned into a gigantic pie";
# invoke function and assign result to array
@words = &split_me;
# loop for each element of array
foreach $word (@words)
{
print "Word: $word\n";
$count++;
}
# print total
print "The number of words in the given string is $count\n";
The output is
Word: The
Word: cow
Word: jumped
Word: over
Word: the
Word: moon
Word: and
Word: turned
Word: into
Word: a
Word: gigantic
Word: pumpkin
The number of words in the given string is 12
This article copyright Melonfire 2000. All rights reserved.