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

Dear Monks,
I have searched without joy for the answer to the following:
print [("foo","bar")]->[1] returns bar, as I'd expect.
Unfortunately, print {("foo","bar")}->{foo} returns syntax error at -e line 1, near "}->".
$h = {("foo","bar")}; print $h->{foo} works fine - so what am I doing wrong?

Replies are listed 'Best First'.
Re: Getting element of anonymous hashref
by Corion (Patriarch) on Oct 16, 2006 at 12:47 UTC

    Perl interprets

    {("foo","bar")}

    as a code block containing two constants, as you can see by the warnigns Perl gives:

    perl -we "{('foo','bar')}" Useless use of a constant in void context at -e line 1. Useless use of a constant in void context at -e line 1.

    You need to tell Perl that you mean a hash constructor instead of a code block by prepending (for example) a + to the expression:

    perl -we "+{(foo => 'bar')}" Useless use of single ref constructor in void context at -e line 1.

    If you put that together, it works:

    perl -we "print +{(foo => 'bar')}->{foo}" bar
      Many thanks! *blushes for having omitted -w flags*
Re: Getting element of anonymous hashref
by blazar (Canon) on Oct 16, 2006 at 13:31 UTC
    print [("foo","bar")]->[1] returns bar, as I'd expect.

    In addition to the answer you already got, please note that also with an anonymous arrayref those parens are not necessary, you can write ["foo","bar"] instead, and for ease of use, especially with a higher number of items, [qw/foo bar/].

    With a hashref they're not only not necessary, but they also confuse the interpreter that choses to disambiguate the "wrong" (wrt your expectations) way in a situation like the one you've met. I believe you may also further disambiguate like thus:

    $ perl -le 'print +{("foo","bar")}->{foo}' bar

    Yep! It works... but of course there's no point doing so when simply ditching the parens would do in the first place. While we're here I'll also remind you that while your syntax is perfectly fine, people tend to prefer a fat comma a.k.a. => to separate key/value pairs since

    1. it logically stresses the relationship between them;
    2. it also autoquotes the key if it's a bare"word".
Re: Getting element of anonymous hashref
by cephas (Pilgrim) on Oct 16, 2006 at 12:54 UTC
    Works fine if you ditch the parens.