Jagmal Jagmal - 6 months ago 14
Perl Question

Is there any way to use a "constant" as hash key in Perl?

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.

Answer

use constant actually makes constant subroutines.

To do what you want, you need to explicitly call the sub:

use constant X => 1;

my %x = ( &X => 'X');

or

use constant X => 1;

my %x = ( X() => 'X');