9

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
}
ThisSuitIsBlackNot
  • 23,492
  • 9
  • 63
  • 110
netdjw
  • 5,419
  • 21
  • 88
  • 162
  • 7
    You shouldn't call functions using the `&mySub` syntax; just use `mySub`. See [When should I use the & to call a Perl subroutine?](http://stackoverflow.com/questions/1347396/when-should-i-use-the-to-call-a-perl-subroutine) – ThisSuitIsBlackNot Apr 27 '15 at 15:23
  • 2
    FYI (and for future googlers, since this seems like a good canonical question), what you're describing are often called "named parameters" or "named arguments." – ThisSuitIsBlackNot Apr 27 '15 at 15:35
  • 1
    @ThisSuitIsBlackNot: that question addresses when you should use `&` and when you absolutely should not. It and its answers do not support a broad "You shouldn't call functions using &" edict. – ysth Apr 27 '15 at 17:34
  • 2
    @ysth Perhaps I should have prefaced my comment with "in general." The vast majority of people who post here using the `&` syntax think it's required for all function calls and have no idea what the implications are, so I think saying "don't do that" and including a link to a more nuanced explanation is sufficient. – ThisSuitIsBlackNot Apr 27 '15 at 17:48

2 Answers2

19

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
}
RobEarl
  • 7,862
  • 6
  • 35
  • 50
0

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};
}
Volodymyr Melnyk
  • 383
  • 3
  • 13