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

前端 未结 9 1766
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;
    
    

提交回复
热议问题