Arguments, return value and the my operator

As with built-in functions, a user-defined function may receive a list of arguments, perform a set of commands and return a value.

The my operator specifies private variables of the function.

Example #1

The following program contains a user-defined function, named calc_average, that receives two numbers and returns their average.

The program passes the numbers 6 and 10 to the subroutine and then prints the returned average.


$a = 6;
$b = 10;

$average = calc_average ($a, $b);  # subroutine invocation.

print "$average\n";

# subroutine definition starts here

sub calc_average {

   my ($x, $y) = @_;
   my ($result);

   $result = ($x + $y) / 2;
   return $result;

# the program will print: 8


Table of Contents.
Previous | Next.