{ "A/B.c" => { "funct1" => 1 -6ren">
gpt4 book ai didi

perl - Perl 的 "exists"可以修改数据结构值吗?

转载 作者:行者123 更新时间:2023-12-03 21:08:31 24 4
gpt4 key购买 nike

我有一个嵌套的哈希表,如下所示:

my %myhash = (
"val1" => {
"A/B.c" => {
"funct1" => 1
}
},
"val2" => {
"C/D.c" => {
"funct2" => 1
}
}
)

我对这个数据结构的目标是根据某些哈希表是否存在来产生不同的值。例如,
sub mysub
{
my $val = shift;
my $file = shift;
my $funct = shift;

if (exists $myhash{$val}{$file}{$funct}) {
return "return1";
}
if (exists $myhash{$val}{$file}) {
return "return2";
}
return "return3";
}

我遇到的行为如下。我有一个时间实例
我的 $val = "val1";
我的 $file = "C/D.c";
我的 $funct = "funct3";

此时,返回值我得到“return2”。这些是我对 Perl 调试器的观察:
  • 在 mysub 中的第一个“if”处中断
  • 打印 p $proxToBugs{"val1"}{"C/D.c"} ==> 返回空行。好的。继续并跳过这个“如果”。
  • 继续并在 mysub 中的第二个“if”处中断
  • 打印 p $proxToBugs{"val1"}{"C/D.c"} ==> 返回“HASH(0x...)”。 WTF时刻。函数返回“return2”。

  • 这告诉我运行第一个 if 修改了数据结构,这允许第二个 if 在实际上不应该通过时通过。我正在运行的函数与上面显示的函数相同;这个只是经过 sanitizer 。有没有人给我解释一下? :)

    最佳答案

    是的。这是因为 autovivification .见底部 exists 文档:

    Although the mostly deeply nested array or hash will not spring into existence just because its existence was tested, any intervening ones [autovivified arrays or hashes] will [spring into existance]. Thus $ref->{"A"} and $ref->{"A"}->{"B"} will spring into existence due to the existence test for the $key element above. This happens anywhere the arrow operator is used...



    其中“...测试上面的 $key 元素...”是指:
    if (exists $ref->{A}->{B}->{$key})  { }
    if (exists $hash{A}{B}{$key}) { } # same idea, implicit arrow

    快乐编码。

    关于perl - Perl 的 "exists"可以修改数据结构值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6887075/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com