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

前端 未结 9 1722
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:19

    Another option is to not use the use constant pragma and flip to Readonly as per recommendations in the Perl Best Practices by Damian Conway.

    I switched a while back after realizing that constant hash ref's are just a constant reference to the hash, but don't do anything about the data inside the hash.

    The readonly syntax creates "normal looking" variables, but will actually enforce the constantness or readonlyness. You can use it just like you would any other variable as a key.

    
    use Readonly;
    
    Readonly my $CONSTANT => 'Some value';
    
    $hash{$CONSTANT} = 1;
    
    
    0 讨论(0)
  • 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' );
    
    0 讨论(0)
  • 2021-02-03 21:24

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

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

    0 讨论(0)
提交回复
热议问题