in reply to Re^2: Module constant and constants in Hashes
in thread Module constant and constants in Hashes
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Module constant and constants in Hashes
by tinita (Parson) on Jan 15, 2009 at 15:14 UTC |