Is there any way to use a “constant” as hash key i

2019-03-11 16:25发布

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.

9条回答
Anthone
2楼-- · 2019-03-11 17:12

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' );
查看更多
祖国的老花朵
3楼-- · 2019-03-11 17:12

Use $hash{CONSTANT()} or $hash{+CONSTANT} to prevent the bareword quoting mechanism from kicking in.

From: http://perldoc.perl.org/constant.html

查看更多
Ridiculous、
4楼-- · 2019-03-11 17:15

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:

use constant X => 1;
%hash = (X() => 1);
%hash = (+X => 1);
$hash{X()} = 1;
$hash{+X} = 1;

In initializers, you could also use the plain comma instead:

%hash = (X, 1);
查看更多
登录 后发表回答