Alex Rivera | Logout

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

Asked 2008-09-18T20:54:25.853
36

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.

Edit
Report

2 Answers

18

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:

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

Or, you can add various punctuation so that you no longer have a simple word in front of the =>:

my %x = ( X() => 'X' );
my %x = ( &X => 'X' );
answered 2008-09-18T20:57:32.650
2

One way is to encapsulate X as (X):

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

Another option is to do away with '=>' and use ',' instead:

my %x ( X, 1 );
answered 2008-09-18T20:58:25.127

Your Answer