develooper Front page | perl.perl5.porters | Postings from May 2012

Re: [perl #112732] Subs ending in { @a } return list, not hashref;can Perl defend against this trap?

Thread Previous | Thread Next
From:
H.Merijn Brand
Date:
May 3, 2012 02:10
Subject:
Re: [perl #112732] Subs ending in { @a } return list, not hashref;can Perl defend against this trap?
Message ID:
20120503111043.26a46fe3@pc09.procura.nl
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


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About