Subroutines

Declaring

sub foo;

Defining

sub foo {
my $arg1 = $_[0];
...
}
sub bar {
my ($arg1, $arg2, $arg3) = @_;
...
}
  • Subroutines cannot be nested
  • Subroutines can be defined anywhere outside of a block
  • Subroutines can recursively call themselves
  • Subroutines are untyped

Arguments

  • Arguments are contained within the special array @_ ; its elements are aliases (i.e. passed by reference) for the actual scalar parameters
my $arg1 = $_[0];
my ($arg1, $arg2, $arg3) = @_;
my $arg1 = shift;   # Remove and return the first argument
  • Arguments are flattened and merged into a single array, as happens in a list context:
sub foo {
# As called below, @_ will have the value ("one", "two", "three", "four", "five");
}

foo( ("one", "two"), "three", ("Four", "five") );
  • To prevent array and hash arguments from being flattened, pass a reference to each:
sub foo {
my ($str, $arr_ref, $hash_ref) = @_;
}

my $str = "hello";
my @arr = ("one", "two", "three");
my %hash = (one => 'apple', two => 'orange');
foo($str, \@arr, \%hash); # Pass references to the array and hash arguments

Return value

  • A return statement can be used to exit the subroutine and to state the return value
  • Can return either a list or a scalar
  • By default, the return value is the last expression evaluated
  • If a return statement does not specify a value, the subroutine returns an empty list in list context, the undefined value in scalar context, or nothing in void context

Calling

foo;
foo(arg1, ...);

&foo(arg1, ...);
  • Parentheses for arguments (when calling a subroutine) are optional
  • The leading ampersand is usually optional (and typically omitted)

Resources URL: 
notes/perl/resources
Sources URL: 
notes/perl/sources

See Also