On Wed, 02 May 2012 12:39:45 -0700, Jim Avera (via RT)
<perlbug-followup@perl.org> wrote:
> In the following, Perl silently parses the {...} in the last line
> of each sub as a BLOCK rather than an anonymous-hash constructor.
> The functions return the list (a,1,b,1), not a hahsref
> as the programmer obviously intended:
>
> use struct; use warnings;
> sub f {
> my @keys = ("a","b");
> { map{$_ => 1} @keys }
> }
> sub g { my @a = (a => 1, b => 2); { @a } }
>
> This is a trap. Can Perl do something to save programmers from it?
Yes, either put a + in front of the opening brace or add an explicit
return:
sub f
{
my @keys = ("a", "b");
+{ map { $_ => 1 } @keys }
}
sub g
{
my @a = (a => 1, b => 2);
return { @a }
}
> One solution might be to actually recognize when {...} is the last thing
> in a sub definition and parse it as an expression in that case.
This issue comes back every now and then, and whatever way the current
parsing is modified will break someone elses expectations. The ability
to unambiguate using a + is easy enough to warrant not to change this
> Another might be to warn about *statements* consisting only of
> expressions with no side-effects, which would let the user know that a
> dangling "{ map{$_=>1} @keys }" was not handled by Perl as they expected.
No. Many people use this to explicitely create a scope, possibly with
lexical variable, to avoid side effects or force auto-destruction.
--
H.Merijn Brand http://tux.nl Perl Monger http://amsterdam.pm.org/
using perl5.00307 .. 5.14 porting perl5 on HP-UX, AIX, and openSUSE
http://mirrors.develooper.com/hpux/ http://www.test-smoke.org/
http://qa.perl.org http://www.goldmark.org/jeff/stupid-disclaimers/
Thread Previous
|
Thread Next