in reply to Re: Module constant and constants in Hashes
in thread Module constant and constants in Hashes

Now I tried the following:
my %english_translation = ( NULL => "Zero", 'EINS' => "One", ZWEI() => 'Two', );
And I got:
EINS = One NULL = Zero 2 = Two
I think, I did not understood the explanation with the "fat comma" and the "normal comma", but the parentheses help.

Thank you Barbara

Replies are listed 'Best First'.
Re^3: Module constant and constants in Hashes
by jdporter (Paladin) on Jan 14, 2009 at 15:37 UTC

    => is sometimes called a "fat comma". A normal comma is , ... Try it.

    use constant { NULL => 0, EINS => 1, ZWEI => 2, }; my %english_translation = ( NULL, "Zero", EINS, "One", ZWEI, "Two", ); foreach ( keys %english_translation ) { print "$_ = $english_translation{$_}\n"; }
Re^3: Module constant and constants in Hashes
by shmem (Chancellor) on Jan 14, 2009 at 21:34 UTC

    From perlop:

    The "=>" operator is a synonym for the comma, but forces any word (consisting entirely of word characters) to its left to be interpreted as a string (as of 5.001). This includes words that might otherwise be considered a constant or function call.

    Constants are, in perl, implemented as subroutines which don't take an argument and return the constant's value. That means that

    use constant { NULL => 0, EINS => 1, ZWEI => 2, };

    has the same effect as saying

    sub NULL { return 0; } sub EINS { return 1; } sub ZWEI { return 2; }

    After either method (use constant LIST or setting up subroutines) you can use the sub denominating bare-words in your program, which will be replaced with the associated values by calling their corresponding subroutine.

    But! if you construct your hash as you did,

    my %english_translation = ( NULL => "Zero", 'EINS' => "One", ZWEI() => 'Two', );

    only the key ZWEI will be resolved as a call of a function, because, as per the above snippt from perlfunc, the "=>" (i.e. "fat comma") operator forces any word (consisting entirely of word characters) to its left to be interpreted as a string, so saying EINS => 1 is exactly the same as saying 'EINS' => 1. The list operator "," (i.e. the normal comma) doesn't do that, so saying

    my %english_translation = ( NULL, "Zero", EINS, "One", ZWEI, 'Two', );

    will call the functions associated with NULL, EINS and ZWEI and interpolate their results.

      has the same effect as saying
      sub NULL { return 0; }
      or more accurate, with an empty prototype:
      sub NULL() { return 0; }