Subroutines #4

#0 | #1 | #2 | #3 | #4

Passing arguments to your subroutines

One of the more useful things you can do with a subroutine is have it perform an operation (or set of operations) on some variables. But how do you get the variables passed to the subroutine?

This is where another Perl special variable comes in: @_.

Any arguments passed to a Perl routine come in as the array @_

All parameters are passed as one single, flat list of scalars.

Multiple return values are likewise returned to the caller as one single, flat list of scalars.

Thus, if your subroutine is looking for 2 variables (arguments), they are available like this: $_[0] and $_[1].

Here's an example (I'm sure you can figure out what it does):

doPythagoras(20,21);

Of course, this returns the length of the hypotenuse given the other 2 sides, which are passed to the subroutine in the parentheses.

The 2 variables are available via the @_ array. We don't return a value to the calling script, but instead print the result directly.

Something to note about variables used in subroutines:

A variable declared in a subroutine is only available in that subroutine.

An outer nested subroutine may contain a variable declaration, which IS available to inner subroutines.

This has to do with something called scope. Every variable name has to be stored somewhere - scope determines where that is, and when it is available.

This works:

doPythagoras(20,21);
sub doPythagoras
{
    my $side1=$_[0];
    my $side2=$_[1];
#   my ($side1,$side2) = @_; # <--- could also be written this way
    my $sq1 = $side1**2; 
    my $sq2 = $side2**2;
    my $sq3 = $sq1 + $sq2;
    my $hypo = sqrt($sq3);
    sub doit {
        print "\n\n$hypo\n";
    }
    doit();
}
print "\$hypo: $hypo\n\n";

In the example above, ALL the variables declared in doPythagoras are available inside the doit subroutine. But you cannot access variables declared inside the doPythagoras subroutine outside of that block.

So this would not work:

doPythagoras(20,21);
sub doPythagoras
{
    my ($side1,$side2) = @_;
    my $sq1 = $side1**2;
    my $sq2 = $side2**2;
    my $sq3 = $sq1 + $sq2;
    my $hypo = sqrt($sq3);
    print "Inner \$hypo: $hypo\n";
    sub doit {
       print "Subroutine \$hypo: $hypo\n";
    }
}
doit();
print "\$side1: $side1\n\n";

A variable can be assigned to a subroutine.


sub doPythagoras
{
    my ($side1,$side2) = @_;
    my $sq1 = $side1**2;
    my $sq2 = $side2**2;
    my $sq3 = $sq1 + $sq2;
    my $hypo = sqrt($sq3);
}
my $Hypo = doPythagoras(20,21);
print "\n\n\$Hypo: $Hypo\n\n";

What is interesting is the choice of these particular 2 sides (20 and 21).

If you run this script, you will see the resulting hypotenuse value is 29 - also an integer. These 3 integers are part of an infinite set of numbers known as Pythagorean Triples.