Perl: constant value in a hash key

I am a little surprised. If I use a constant for the hash key, Perl does not use the value. I need to put in front of him for this to happen.

use constant A => "a";
use constant B => "b";

my %h = (A => "1", &B => "2");

print "\n". A . ", " . B;
foreach (sort (keys (%h)))
{
    print "\n"  . $_ . "=" . $h {$_};
}

Conclusion:

a, b
A=1
b=2

But I would expect that (second line is different).

a, b
A=1
b=2

Any way to do this without using and using a constant for the hash key?

Thanks for the help!

+4
source share
1 answer

It is registered in constant under CAVEATS.

A common way is to use ():

my %h = (A => "1", B() => "2");

or switch to a "non-strict bold comma" (or a simple comma):

my %h = (A => "1", B ,=> "2");

Usage &does not embed a constant, as you can check with B :: Deparse :

$ perl -MO=Deparse ~/1.pl
sub B () { 'b' }
use constant ('A', 'a');
use constant ('B', 'b');
my(%h) = ('A', '1', &B, '2');
print "\na, b";
foreach $_ (sort keys %h) {
    print "\n" . $_ . '=' . $h{$_};
}
/home/choroba/1.pl syntax OK
+5
source

Source: https://habr.com/ru/post/1691680/


All Articles