chris01
chris01

Reputation: 12331

Perl: Constant value in hash-key

I am a bit astonished. If I use a constant for a hash-key Perl does not use the value. I need to put & in front of it to make this 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 {$_};
}

Output:

a, b
A=1
b=2

But I would expect that (2nd line is different).

a, b
a=1
b=2

Any way to do it without the & when use the constant for a hash-key??

Thanks for help!

Upvotes: 5

Views: 337

Answers (1)

choroba
choroba

Reputation: 241918

It's documented in constant under CAVEATS.

The common way is to use ():

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

or switch to the "non-stringifying fat comma" (or a simple comma):

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

Using & doesn't inline the constant, as you can verify 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

Upvotes: 5

Related Questions