I just started work with a new team new place. They told me we return ref instead of value in our perl modules. Also I saw something like return +{foo=>'bar'}; and return {foo=>'bar'};
Whats the difference? And whether to return ref or value?
The +
in return +{foo=>'bar'}
is completely useless.
First, some background.
The Perl language has ambiguities. Take for example
sub f {
{ } # Is this a hash constructor or a block?
}
{ }
is valid syntax for a block ("bare loop").{ }
is valid syntax for a hash constructor.
And both are allowed as a statement!
So Perl has to guess. Perl usually guesses correctly, but not always. You can give it "hints". Unary-+
can be used to do this. Unary-+
is a completely transparent operator; it does nothing at all. However, it must be followed by an expression (not a statement). { }
has only one possible meaning as an expression.
+{ } # Must be a hash constructor.
Similarly, you can trick Perl to guess the other way.
{; } # Perl looks ahead, and sees that this must be a block.
Here's an example where Perl guesses wrong:
map { {} } 1..5 # ok. Creates 5 hashes and returns references to them.
map {}, 1..5 # XXX Perl guesses you were using "map BLOCK LIST".
map +{}, 1..5 # ok. Perl parses this as "map EXPR, LIST".
As for the code in the question, return
must be followed by an expression (if anything), so there's only one possible interpretation for return { ... };
, so the +
is completely useless there.
Most people only disambiguate when necessary. Others might add +
whenever it's ambiguous (even if Perl would guess right). But this is the first time I've heard of using +
in front of every hash constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With