How can I create a subroutine that can parse arguments like this:
&mySub(arg1 => 'value1', arg2 => 'value2' ...);
sub mySub() {
# what do I need to do here to parse these arguments?
# no arguments are required
}
Passing Arguments to a Subroutine You can pass various arguments to a subroutine like you do in any other programming language and they can be acessed inside the function using the special array @_. Thus the first argument to the function is in $_[0], the second is in $_[1], and so on.
There is a functional difference ... shift modifies @_ while assignment does not.
A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again.
Simply assign the input array to a hash:
sub my_sub {
my %args = @_;
# Work with the %args hash, e.g.
print "arg1: ", $args{arg1};
}
If you want to provide default values, you can use:
sub my_sub {
my %args = ( 'arg1' => 'default arg1',
'arg2' => 'default arg2',
@_ );
# Work with the (possibly default) values in %args
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With