in reply to Is an empty block not a block?

Any set of braces that isn't part of another expression (such as an if-block or a variable usage) are interpreted as either a hash ref or block of code. Perl uses heuristics to figure out which. If you find that Perl is guessing wrong, you can make it look more like what you want it to be.

Generally speaking, an empty set is going to be treated as a hashref. If, for some unfathomable reason, you want a no-op block, stick a semicolon inside it:

perl -we "use strict; {;} no strict 'refs';"
Perl sees that you've got code (an empty statement) in there, so it must be a code block. No warning about Useless use of single ref constructor like you'd get if you used {}; instead. (I turned on warnings so you could see a difference.)

Conversely, if you want to make Perl interpret what looks like a block of code to be a hashref, put it in parentheses or stick a plus on the front. (I personally dislike the + convention.)

F:\Perl>perl -we "use strict; {qw(key val)}; no strict 'refs';" Useless use of a constant in void context at -e line 1. Useless use of a constant in void context at -e line 1. F:\Perl>perl -we "use strict; ({qw(key val)}); no strict 'refs';" Useless use of single ref constructor in void context at -e line 1
The second example is half as useless. :-)

Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^2: Is an empty block not a block?
by diotalevi (Canon) on Nov 18, 2005 at 22:29 UTC

    You could also prefix the hash with "scalar." That's especially clear.

    return scalar { ... };