Perl: Function

By Xah Lee. Date: . Last updated: .

Define Function (subroutine)

Here is a example of a function.

use Data::Dumper;
$Data::Dumper::Indent = 0;  # print in compact style

# define a function
sub ff {
  $a = $_[0];
# get first arg
  $b = $_[1];
# get second arg

  # arguments are automatically assigned to array @_
  print Dumper(\@_);  # prints the array @_

  # use “return” to return value and exit function
  return $a + $b;
}

ff(3, 4, "rabbit");
# $VAR1 = [3,4,'rabbit'];

Note: perl subroutine's parameters are usually not declared.

Arguments are automatically assigned to the array @_.

$_[0] is the first element of the array @_. The @_ array is a predefined array.

Optional Parameters

To define a function with optional parameters, just use defined($_[n]) to check if the argument is given.

# myFun(x,y) returns x+y. y is optional and default to 1.
sub myFun {
  $x = $_[0];

  if (defined $_[1]) {
    $y = $_[1];
  } else {
    $y = 1;
  }

  return $x+$y;
}

print myFun(3);
# 4

perldoc perlsub