In Perl, on what basis should one choose between passing a reference to a hash/array and passing a hashref/arrayref scalar?
To be brief, I'm wondering if there are any best-practice reasons for deciding between:
my %hash = 开发者_StackOverflow中文版( foo => 1, bar => 2 );
# some in-between logic
some_func(\%hash);
and
my $hashref = { foo => 1, bar => 2 };
# some in-between logic
some_func($hashref);
Or is purely a style decision?
The two are equivalent and interchangeable. The decision should be made based on what is clearest for you.
You can also move back and forth:
my $hashref = {x => 1, y => 2};
our %hash; *hash = $hashref;
some_func($hashref);
some_func(\%hash); # \%hash == $hashref
In general I prefer to work with the plural forms %name
and @name
since it results in less line noise due to dereferencing. That and some_func(\%var)
is clearer with regard to var
's type than some_func($var)
These two examples do exactly the same thing. So it mainly depends on which is more convenient for what else, if anything, you do with the %list
variable and/or $listref
variable.
Or maybe you'd like to skip the extra variable entirely:
some_func( { foo => 1, bar => 2 } );
(Less likely now that you've added those "in-between logic" comments.)
As indicated above, they're the same though the first may give you better context to what type of variable (i.e. a hash) you're using in your "some in-between logic" code.
In most cases it won't make a difference, but I have had some nasty bugs that occurred from trying to change where my reference points if I pass in a reference-of list.
Unless I really want to change the contents of a pre-existing array or hash, I personally favor using anonymous lists/hashes (like your second example).
This is just personal experience, though. I will admit that maybe if I understood Perl better I would know the objective best practices (if any exist).
精彩评论