如何创建一个可以解析这样的参数的子例程:
&mySub(arg1 => 'value1', arg2 => 'value2' ...);
sub mySub() {
# what do I need to do here to parse these arguments?
# no arguments are required
}
答案 0 :(得分:17)
只需将输入数组分配给哈希:
sub my_sub {
my %args = @_;
# Work with the %args hash, e.g.
print "arg1: ", $args{arg1};
}
如果要提供默认值,可以使用:
sub my_sub {
my %args = ( 'arg1' => 'default arg1',
'arg2' => 'default arg2',
@_ );
# Work with the (possibly default) values in %args
}
答案 1 :(得分:0)
也许你会发现Method::Signatures
模块非常有用,它可以让你做类似的事情:
func MySub (Str :$arg1 = 'default arg1', Str :$arg2 = 'default arg2') {
print "arg1: ", $arg1};
}