The my operator specifies private variables of the function.
The program passes the numbers 6 and 10 to the subroutine and then prints the returned average.
#!/usr/local/bin/perl
$a = 6;
$b = 10;
$average = calc_ave ($a, $b); # subroutine invocation.
print "$average\n";
# subroutine definition starts here
sub calc_ave {
my ($x, $y) = @_;
my ($result);
$result = ($x + $y) / 2;
return $result;
}
# the program will print: 8
$average = calc_ave ($a, $b);Where $a and $b are the arguments passed to the subroutine.
In this example, inside calc_ave the @_ array will contain (6, 10).
my ($var1, $var2, $var3 ...) = @_;And in this example:
my ($x, $y) = @_;
In this example, the subroutine returns the value of $result, using the command:
return $result;
A function may also return a list value, e.g.
return ($n, $m, $k); or return (@arr);
calc_ave ($a, $b);then gets the value returned by the subroutine. In this example, it will become 8.
Normally, the subroutine invocation expression is assigned to some variable (here: $average), which will then contain the subroutine return value:
$average = calc_ave ($a, $b);
However, note that you can also use the subroutine invocation expression
directly in some other operation. e.g. you can directly print it:
print calc_ave($a, $b), "\n";
or include it in an arithmetical calculation:
$net = calc_ave($a, $b) - $background;