Reputation: 6007
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
}
Upvotes: 9
Views: 1007
Reputation: 482
Maybe you'll also find very useful the Method::Signatures
module, which will allow you to do something like that:
func MySub (Str :$arg1 = 'default arg1', Str :$arg2 = 'default arg2') {
print "arg1: ", $arg1};
}
Upvotes: 0
Reputation: 7912
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
}
Upvotes: 19