2017-12-03 16:06:03 +00:00
|
|
|
# The reserved word 'sub' defines a subroutine.
|
|
|
|
|
|
|
|
# Basic subroutine with on parameter:
|
|
|
|
sub mysub {
|
|
|
|
my $param = shift;
|
2018-07-27 17:55:28 +00:00
|
|
|
#
|
2017-12-03 16:06:03 +00:00
|
|
|
# Do stuff here
|
|
|
|
return $myvalue
|
|
|
|
}
|
|
|
|
$x = mysub( "value" )
|
|
|
|
|
|
|
|
# Named parameters to subroutines:
|
|
|
|
sub named_params_example {
|
|
|
|
my ( $arg ) = @_;
|
|
|
|
# Use my ( $self, $arg ) = @_; if you are in object land.
|
2018-07-27 17:55:28 +00:00
|
|
|
#
|
2017-12-03 16:06:03 +00:00
|
|
|
say $arg->{one};
|
|
|
|
say $arg->{two};
|
|
|
|
}
|
2018-07-27 17:55:28 +00:00
|
|
|
#
|
|
|
|
# Calling the above subroutine:
|
2017-12-03 16:06:03 +00:00
|
|
|
named_params_example({
|
|
|
|
one => "First argument",
|
|
|
|
two => "Second argument"
|
|
|
|
});
|
|
|
|
|
|
|
|
# Named parameters with default values:
|
|
|
|
sub named_params_with_defaults {
|
|
|
|
my ( $arg ) = @_;
|
|
|
|
# Use my ( $self, $arg ) = @_; if you are in object land.
|
2020-02-22 02:47:54 +00:00
|
|
|
#
|
2017-12-03 16:06:03 +00:00
|
|
|
# Set defaults
|
|
|
|
# If option given Use options Else
|
|
|
|
my $one = exists $arg->{one} ? $arg->{one} : "default1";
|
|
|
|
my $two = exists $arg->{two} ? $arg->{two} : "default2";
|
|
|
|
}
|
2018-07-27 17:55:28 +00:00
|
|
|
#
|
2017-12-03 16:06:03 +00:00
|
|
|
named_params_with_defaults({ one => "override arg 'one'" });
|
|
|
|
|
|
|
|
# Return named params from a subroutine:
|
|
|
|
sub foo {
|
|
|
|
my $clause = 'This is a clause';
|
|
|
|
my @param = qw/ one two thee /;
|
|
|
|
return ({
|
|
|
|
clause => $clause,
|
|
|
|
params => \@param
|
|
|
|
});
|
|
|
|
}
|
2018-07-27 17:55:28 +00:00
|
|
|
#
|
2017-12-03 16:06:03 +00:00
|
|
|
my $r = foo();
|
2018-07-27 17:55:28 +00:00
|
|
|
#
|
2017-12-03 16:06:03 +00:00
|
|
|
say "clause = [$r->{clause}]";
|
|
|
|
for my $p ( @{ $r->{params} } ) {
|
|
|
|
say "param = [$p]";
|
|
|
|
}
|
|
|
|
|
|
|
|
# More help with Perl's fabulous perldoc command:
|
|
|
|
perldoc sub
|