Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between returning +{} or {} in perl from a function, and return ref or value

Tags:

perl

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?

like image 449
Sahib Khan Avatar asked Feb 07 '17 21:02

Sahib Khan


1 Answers

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.

like image 168
ikegami Avatar answered Oct 03 '22 14:10

ikegami