这个程序的输出是:
Key1=1, Key2=status, value=0
Key1=1, Key2=suffix, value=B
Key1=1, Key2=consumption, value=105
Key1=0, Key2=status, value=0
Key1=0, Key2=suffix, value=B
Key1=0, Key2=consumption, value=105
如果你在运行时看到了不同的东西,请指出你所看到的。
没有腐败,也没有复制。 %th1
包含指向单个其他哈希的指针。
一个内存位置有一个哈希,另一个内存位置有另一个哈希。当你修改%th2
时,它会改变。
稍微修改一下,这样我就可以有一个更紧凑的输出,并且能够调用 display 作为一个函数。
#!/usr/bin/perl
my %th1 = ();
my %th2 = ();
$th2{"suffix"} = "A";
$th2{"status"} = 0;
$th2{"consumption"} = 42;
$th1{0} = \%th2;
print "--- After first block:\n";
display(\%th1);
$th2{"suffix"} = "B";
print "--- Modified th2 suffix to B:\n";
display(\%th1);
$th2{"status"} = 0;
$th2{"consumption"} = 105;
print "--- finished modification of th2:\n";
display(\%th1);
$th1{1} = \%th2;
print "--- after assignment to th1{1} :\n";
display(\%th1);
exit;
sub display {
my $hr = shift;
for my $key1 (keys %$hr) {
print "$key1:\n";
for my $key2 (keys %{$hr->{$key1}}) {
print "\t$key2 = $hr->{$key1}{$key2}\n";
}
}
}
这个的输出是:
--- After first block:
0:
status = 0
suffix = A
consumption = 42
--- Modified th2 suffix to B:
0:
status = 0
suffix = B
consumption = 42
--- finished modification of th2:
0:
status = 0
suffix = B
consumption = 105
--- after assignment to th1{1} :
1:
status = 0
suffix = B
consumption = 105
0:
status = 0
suffix = B
consumption = 105
您可以在 中的取消引用值中看到%th2
生效的修改%th1
。
让我们以不同的方式看待这个......而不是打印出值,让我们打印出%th1
包含的内容?两个变化......添加了行以显示顶部附近的内存:
my %th1 = ();
my %th2 = ();
print \%th1, "\t", \%th2,"\n"; # this line added
并display
改变:
sub display {
my $hr = shift;
for my $key1 (keys %$hr) {
print "$key1 --> $hr->{$key1}\n";
}
}
现在输出是:
HASH(0x239edb0) HASH(0x239edf8)
--- After first block:
0 --> HASH(0x239edf8)
--- Modified th2 suffix to B:
0 --> HASH(0x239edf8)
--- finished modification of th2:
0 --> HASH(0x239edf8)
--- after assignment to th1{1} :
1 --> HASH(0x239edf8)
0 --> HASH(0x239edf8)
的值%th1
一直指向单个散列。没有副本,只有一个在%th1
.
很有可能,您希望在每个位置都有单独的值。这最容易通过创建匿名哈希并分配:
#!/usr/bin/perl
my %th1 = ();
my %th2 = ();
$th1{0} = {"suffix" => "A", "status" => 0, "consumption" => 42 };
print "--- After first block:\n";
display(\%th1);
$th1{1} = {"suffix" => "B", "status" => 0, "consumption" => 105 };
print "--- after assignment to th1{1} :\n";
display(\%th1);
exit;
sub display {
my $hr = shift;
for my $key1 (keys %$hr) {
print "$key1: $hr->{$key1}\n";
for my $key2 (keys %{$hr->{$key1}}) {
print "\t$key2 = $hr->{$key1}{$key2}\n";
}
}
}
哪个打印:
--- After first block:
0: HASH(0xcf6998)
status = 0
suffix = A
consumption = 42
--- after assignment to th1{1} :
1: HASH(0xd143c0)
status = 0
suffix = B
consumption = 105
0: HASH(0xcf6998)
status = 0
suffix = A
consumption = 42
您可以看到两个单独的内存地址和两组单独的值。