2015-04-27 9 views
9

Come posso creare una subroutine in grado di analizzare argomenti come questo:Perl argomenti subroutine come un hash

&mySub(arg1 => 'value1', arg2 => 'value2' ...); 

sub mySub() { 
    # what do I need to do here to parse these arguments? 
    # no arguments are required 
} 
+7

Non dovresti chiamare le funzioni usando la sintassi '& mySub'; usa semplicemente 'mySub'. Vedi [Quando dovrei usare il & per chiamare una subroutine Perl?] (Http://stackoverflow.com/questions/1347396/when-should-i-use-the-call-a-perl-subroutine) – ThisSuitIsBlackNot

+2

FYI (e per i futuri googler, dal momento che questa sembra una buona domanda canonica), quelli che stai descrivendo sono spesso chiamati "parametri con nome" o "argomenti con nome". – ThisSuitIsBlackNot

+1

@ThisSuitIsBlackNot: quella domanda si rivolge quando devi usare '&' e quando non devi assolutamente. Esso e le sue risposte non supportano un ampio "Non si dovrebbero chiamare funzioni usando &" editto. – ysth

risposta

18

Basta assegnare la matrice di ingresso ad un hash:

sub my_sub { 
    my %args = @_; 
    # Work with the %args hash, e.g. 
    print "arg1: ", $args{arg1}; 
} 

Se si desidera fornire i valori di default, è possibile utilizzare:

sub my_sub { 
    my %args = ('arg1' => 'default arg1', 
       'arg2' => 'default arg2', 
       @_); 
    # Work with the (possibly default) values in %args 
} 
0

Forse troverete anche molto utile il Method::Signatures modu le, che ti permetterà di fare qualcosa del genere:

func MySub (Str :$arg1 = 'default arg1', Str :$arg2 = 'default arg2') { 
    print "arg1: ", $arg1}; 
}