Is there any way to use a constant as a hash key?
For example:
use constant X => 1;
my %x = (X => 'X');
The above code will create a hash with "X" as key and not 1 as key. Whereas, I want to use the value of constant X as key.
Is there any way to use a constant as a hash key?
For example:
use constant X => 1;
my %x = (X => 'X');
The above code will create a hash with "X" as key and not 1 as key. Whereas, I want to use the value of constant X as key.
Your problem is that => is a magic comma that automatically quotes the word in front of it. So what you wrote is equivalent to ('X', 'X').
The simplest way is to just use a comma:
Or, you can add various punctuation so that you no longer have a simple word in front of the =>:
Use
$hash{CONSTANT()}
or$hash{+CONSTANT}
to prevent the bareword quoting mechanism from kicking in.From: http://perldoc.perl.org/constant.html
The
use constant
pragma creates a subroutine prototyped to take no arguments. While it looks like a C-style constant, it's really a subroutine that returns a constant value.The
=>
(fat comma) automatically quotes left operand if its a bareword, as does the $hash{key} notation.If your use of the constant name looks like a bareword, the quoting mechanisms will kick in and you'll get its name as the key instead of its value. To prevent this, change the usage so that it's not a bareword. For example:
In initializers, you could also use the plain comma instead: