perl:从包含对它的引用的哈希中打印一个字符串

ewo*_*wok 3 perl

对不起,如果这是一个糟糕的标题.

我有以下哈希:

my %map = (
    'key1', 'hello',
    'key2', \'there'
);
print Dumper(\%map);
Run Code Online (Sandbox Code Playgroud)

输出:

$VAR1 = {
    'key2' => \'there',
    'key1' => 'hello'
};
Run Code Online (Sandbox Code Playgroud)

我想打印出来的价值'key2'.这是我尝试过的:

print "$map{key2}" => SCALAR(0x2398b08)
print "$$map{key2}" =>
print "$map->{key2}" =>
Run Code Online (Sandbox Code Playgroud)

我的目标:

print [some magic thing] => there
Run Code Online (Sandbox Code Playgroud)

我是perl的新手,所以我还没有100%明白引用的行为方式以及如何取消引用它们.我如何得到我正在寻找的东西?

ike*_*ami 5

$map{key2}返回所需元素的值.元素是对字符串的引用.[1]如果要打印该引用引用的字符串,则需要取消引用它.

say ${ $map{key2} };
Run Code Online (Sandbox Code Playgroud)

参考文献:


  1. 我怀疑这是故意的!这肯定表明某处出错.


Bor*_*din 5

$map{key2}是对标量值的引用\'there',因此您需要取消引用它

$$map{key2}$map->{key2}两者都将其视为$maphash 的引用,但它甚至不存在,所以这是错误的

您必须使用大括号来消除求值顺序的歧义

${ $map{key2} }
Run Code Online (Sandbox Code Playgroud)

就是你想要的。或者也可以分两步写

my $val = $map{key2};
print $$val, "\n";
Run Code Online (Sandbox Code Playgroud)