Perl:如何在哈希中获取对与键相关联的值的引用[已关闭]

46scxncf  于 2022-11-15  发布在  Perl
关注(0)|答案(1)|浏览(127)

**已关闭。**此问题为not reproducible or was caused by typos。目前不接受答案。

这个问题是由一个打字错误或一个无法再重现的问题引起的。虽然类似的问题在这里可能是on-topic,但这个问题的解决方式不太可能帮助未来的读者。
四个月前关门了。
Improve this question
假设我有一个由h引用的hash,其中包含键a。我想把bMap到一个hash。我可以直接使用$h->{b}{key} = 123来完成这个操作,但是如果我插入多个键/值对,效率会很低,因为我需要多次执行$h->{b}查找,而且很罗嗦。如果只有两个级别,也不算太糟糕。但在我的脚本中,我实际上有 * 多 * 级哈希。例如:
$h1->{one}{two}{key} = 123
我想做的是获得一个对与键相关的值的位置的引用。如果那里什么都没有,解释器应该为我构造一个哈希值。下面是我尝试的:

#!/usr/bin/perl -l

use Data::Dumper;

# create a hash
$h = {a => 1};
print Data::Dumper->Dump([$h], ["h"]);

# take a reference to the value associated with key "b"
$bref = \$h->{b};
print 'bref = '. $bref;
print Data::Dumper->Dump([$bref], ["bref"]);

# construct a hash and assign its address to the location pointed to by bref -- the value associated with "b" in the hash
$$bref->{foo} = 10;
$$bref->{bar} = 20;
$$bref->{baz} = 30;
print 'bref = '. $bref;
print Data::Dumper->Dump([$bref], ["bref"]);

# it doesn't work
$h = {a => 1};
print Data::Dumper->Dump([$h], ["h"]);

bref指的是常量值undef;当我把它解引用为一个hash时,解释器确实构造了一个hash,但是它是独立的,不在h中。

~/perl: perl ref-to-hash-value
$h = {
       'a' => 1
     };

bref = SCALAR(0x13b50f8)
$bref = \undef;

bref = REF(0x13b50f8)
$bref = \{
            'foo' => 10
          };

$h = {
       'a' => 1
     };

有没有一种方法可以做到我想要的?或者有没有另一种方法可以解决我描述的问题?

eqqqjvef

eqqqjvef1#

我 的 脚本 有 一 个 错误 :我 在 倒数 第 二 行 将 h 重新 分配 给 一 个 新 的 哈希 值 , 当 我 删除 该行 时 , 它 就 可以 工作 了 :

~/perl: perl ref-to-hash-value
$h = {
       'a' => 1
     };

bref = SCALAR(0x98c0f8)
$bref = \undef;

bref = REF(0x98c0f8)
$bref = \{
            'baz' => 30,
            'foo' => 10,
            'bar' => 20
          };

$h = {
       'b' => {
                'baz' => 30,
                'foo' => 10,
                'bar' => 20
              },
       'a' => 1
     };

中 的 每 一 个

相关问题