I see people using two styles for passing named parameters in Perl:
use strict;
use warnings;
use Data::Dumper;
sub foo {
print Dumper @_;
}
sub bar {
print Dumper @_;
}
foo( A => 'a', B => 'b' );
bar( { A => 'a', B => 'b' } );
What are the advantages in using foo() style instead of bar() style?
The second method passes a reference to hash, while the first just passes a list.
There are two aspects here: in theory, a reference to hash could be better in terms of performance, though for short argument lists this is negligible. For a simple call like
foo(a => 1, b => 2)there is no performance difference, because@_is actually an alias to the original values.But if the caller already has the values in a hash, the first style requires conversion from hash to list, and then back again to hash, which can be slow.
The second aspect is the question who is responsible for the conversion to a hash. The first style leaves it up the function being called, and if that just does
my %args = @_, it will produce curious warnings if the argument list is not of even length.That’s why I slightly prefer the second style (or I use Perl 6, which supports named arguments natively).