Perl Subroutines

From Wiki
Jump to navigation Jump to search

Define

sub hypotenuse {
    return sqrt( ($_[0] ** 2) + ($_[1] ** 2) ); # "return" is optional
}
sub print_name_and_age {
    my ($name, $age) = @_;   # @_ is the calling context array
    print "$name is $age years old.\n";
    my $same_name = $_[0];   # first arg of @_ array
}

Call

$diag = hypotenuse(3,4);  # $diag is 5
$diag = &hypotenuse(3,4);  # the & is optional
print_name_and_age("Lassie", 3); # @_ defined to be ("Lassie", 3)

Required arguments

Change the first line above to

sub print_name_and_age($$) {

to require two scalar arguments.

Passing arrays and hashes

Use references to operate on the passed data

sub my_function($$){
    my %hash = %{$_[0]};
    my @array = @{$_[1]};
    ...
}
my_function(\%the_hash, \@the_array);

A subroutine may return an array or hash, too.