The Perl language has ambiguities. Take for example
sub some_sub {
{ } # 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. In your case, it guessed correctly for f()
, but not for g()
.
To fix this, you can give Perl "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.
So in this case, you could use
sub g { +{
%{f()},
c => 3,
d => 4,
} }
or
sub g { return {
%{f()},
c => 3,
d => 4,
} }
(return
must also be followed by an expression if anything.)