in reply to explanation of constant syntax?

"use constant" creates a parameter-less subroutine to define the constant. Unfortunately, the quoting of a hash key bareword and the bareword quoting to the left of a fat arrow are stronger than the execution of subroutine to get its value.

A simple workaround is to add an extra set of parens:

my %hash = ( (FOO) => 35, (BAR) => 19, ); print $hash{(FOO)};
There are other ways around, but I think this is the cleanest.

-- Randal L. Schwartz, Perl hacker
Be sure to read my standard disclaimer if this is a reply.

Replies are listed 'Best First'.
Re: explanation of constant syntax?
by meonkeys (Chaplain) on Mar 20, 2004 at 17:57 UTC

    I understand that the bareword FOO inside the parens is similar to when it's inside @{[...]} because it causes the subroutine created by the constant pragma to be called rather than FOO to simply be used as a hash key.

    Would you elucidate on why this happens or point me to the right perldoc to read on this subject?

    ---
    "A Jedi uses the Force for knowledge and defense, never for attack."
      Well, just break it apart:
      [ ... ]
      creates an arrayref pointing to its contents, in this case FOO (not quoted, so we get the constant value). And then:
      @{ ... }
      dereferences the enclosed value as if it were an array reference. So essentially, this is the hard way to say:
      ( ... )
      between the two of them, except that it also interpolates within a double-quoted string. That's how I stumbled across this in the first place: how to evaluate a value inside a double-quoted string. I wrote about it in a CLP posting early in the Perl5 days, and the meme stuck and is still being used in other places.

      -- Randal L. Schwartz, Perl hacker
      Be sure to read my standard disclaimer if this is a reply.