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

前端 未结 9 1759
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:18

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

提交回复
热议问题