假设我有一个由h引用的散列,其中包含键a。我想将b映射到散列。我可以直接使用$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;当我将其取消为哈希时,解释器确实会构造哈希,但它是独立的,而不是在h中。下面是脚本的输出:
~/perl: perl ref-to-hash-value
$h = {
'a' => 1
};
bref = SCALAR(0x13b50f8)
$bref = \undef;
bref = REF(0x13b50f8)
$bref = \{
'foo' => 10
};
$h = {
'a' => 1
};有办法做我想做的事吗?或者,对于我描述的问题,还有其他的解决办法吗?
发布于 2022-07-23 01:03:28
我的脚本有一个错误:我将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
};https://stackoverflow.com/questions/73087343
复制相似问题