rovf has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

could someone kindly explain to me, why this innocent little program is syntactically wrong?

use strict; use warnings; my $xnix='X'; sub f { {$xnix => 100}->{'X'} } print f(),"\n";
ActiveState Perl complains:
syntax error at U:\develsv\ARTS\playground\hash_problem.pl line 7, nea +r "}->" syntax error at U:\develsv\ARTS\playground\hash_problem.pl line 8, nea +r "}"
The problem must be related to the usage in a sub, because the similar
use strict; use warnings; my $xnix='X'; my $f={$xnix => 100}->{'X'}; print $f,"\n";
works as expected.

-- 
Ronald Fischer <ynnor@mm.st>

Replies are listed 'Best First'.
Re: Can't see the syntax error here...
by moritz (Cardinal) on Jun 13, 2008 at 11:54 UTC
    Perl tries to parse the curly braces as a block, not a hash ref. Use a + to disambiguate: +{$xnix => 100}->{'X'}

    Update: BTW this is not related to the sub at all, since a simple print {$xnix => 100}->{'X'}; gives the same error.

      Amazing!

      I think I would searched for this for years, but once I see your explanation, it becomes clear.

      BTW, the reason why I thought it would be related to sub is that the similar code

      my $f={$xnix => 100}->{'X'};
      works fine, but of course now this is clear too: In the latter case, there is no ambiguity, so it is correctly parsed as a hash. Thanks a lot for helping!

      -- 
      Ronald Fischer <ynnor@mm.st>
Re: Can't see the syntax error here...
by andreas1234567 (Vicar) on Jun 13, 2008 at 12:00 UTC
    chromatic wrote What's Wrong with Perl 5:
    When is a block a block, and when is it a hash reference?
    Seems like your problem illustrates this point.
    $ perl use strict; use warnings; my $xnix='X'; sub f { my $z = {$xnix => 100}->{'X'}; # make it a hash reference return $z; } print f(),"\n"; __END__ 100
    --
    No matter how great and destructive your problems may seem now, remember, you've probably only seen the tip of them. [1]