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

前端 未结 9 1753
Happy的楠姐
Happy的楠姐 2021-02-03 20:39

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 cr

9条回答
  •  情书的邮戳
    2021-02-03 21:20

    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' );
    

提交回复
热议问题