How to expand hash into argument list in function call in Perl? I am searching Perl equivalent of Python's syntax : so开发者_StackOverflow社区mefunc(**somedict)
or somefunc(*somelist)
. Is that possible in Perl?
In Perl, all function arguments are passed as lists and stored in the special array variable @_
. You can copy those values to some other array, or directly into a hash (as you can with any array/list).
If you are writing a function, you can pass the arguments directly into an array or hash:
sub hashFunc {
my %args = @_;
....
}
sub arrayFunc {
my @args = @_;
...
}
To call a function like that, just pass them as if they were a list or hash:
hashFunc(arg1 => 'someVal', arg2 => 'someOtherVal');
arrayFunc('someVal', 'someOtherVal');
If you already have the arguments in a variable, just pass them along and Perl flattens out the array/hash into the argument list:
hashFunc(%someHash);
arrayFunc(@someArray);
Hashes do expand into a list when calling a function:
my %h = (a => 1, b => 2, c => 3);
sub foo {
# prints the key-value pairs in unsorted order
print "@_\n";
}
foo %h;
精彩评论