简体   繁体   English

Perl:清除嵌套散列中的值

[英]Perl: Clearing values in nested hash

If I have a hash reference defined as:如果我有一个哈希引用定义为:

my %hash1=(
    "a" => 1,
    "b" => 2,
    "c" => {
               "d" => 4,
               "e" => 5
           }
    );

my $r_hash1 = \%hash1;

Would using:会使用:

$r_hash1->{c}=();

To clear the keys in %hash1{c} for reuse be clean?清除 %hash1{c} 中的键以供重用是否干净?

If so, I was also wondering if I had:如果是这样,我也想知道我是否有:

my %hash1=(
    "a" => 1,
    "b" => 2
);

my %hash2=(
    "d" => 4,
    "e" => 5
);

my $r_hash1 = \%hash1;
my $r_hash2 = \%hash2;

$r_hash1->{"c"} = $r_hash2;

Whether using:是否使用:

$r_hash1->{c}=();

Would free the memory used by %hash2 for reuse as surely it would have to be used in hash context:将释放 %hash2 使用的内存以供重用,因为它肯定必须在哈希上下文中使用:

%$r_hash1->{c}

But this would look at $r_hash1 in hash context, rather than the contents of $r_hash1->{c}.但这会在散列上下文中查看 $r_hash1,而不是 $r_hash1->{c} 的内容。

Thanks.谢谢。

If you want to empty out a nested hash (but still have the hash exist) then you need to dereference it first:如果你想清空一个嵌套的散列(但仍然有散列存在),那么你需要先取消引用它:

%{ $r_hash1->{c} } = ( );

Alternatively, you could just assign an empty hashref in its place:或者,您可以在其位置分配一个空的 hashref:

$r_hash1->{c} = { };

In your second example, if you set $r_hash1->{c} = $r_hash2 , and then clear it with %{ $r_hash1->{c} } = ( ) , the stuff in %hash2 will be cleared.在你的第二个例子,如果你设置$r_hash1->{c} = $r_hash2 ,然后清除%{ $r_hash1->{c} } = ( )在东西%hash2被清除。 This is because you are dereferencing $r_hash1->{c} , which is a copy of $r_hash2 , which is a reference to %hash2 .这是因为您正在取消引用$r_hash1->{c} ,它是$r_hash2的副本,它是对%hash2的引用。

Here's a simple program which demonstrates the outcome:这是一个演示结果的简单程序:

perl -MData::Dumper -E '%h1 = ( a => 1, b => 2 ); %h2 = ( d => 4, e => 5 ); $h1{c} = \%h2; say Dumper \%h1; %{ $h1{c} } = ( ); say Dumper \%h1; say Dumper \%h2'
$VAR1 = {
          'c' => {
                   'e' => 5,
                   'd' => 4
                 },
          'a' => 1,
          'b' => 2
        };

$VAR1 = {
          'c' => {},
          'a' => 1,
          'b' => 2
        };

$VAR1 = {};

This is slightly abbreviated (I didn't bother with the intermediate named references.) The first dump shows %h1 with its reference to %h2 .这是稍微缩写(我没有打扰中间命名引用。)第一个转储显示%h1及其对%h2引用。 The second dump shows %h1 after dereferencing the reference and clearing it out.在取消引用引用并将其清除后,第二个转储显示%h1 The third dump shows the original %h2 after it has been cleared.第三个转储显示清除后的原始%h2

On the other hand, if you use $h1{c} = { } , the original %h2 will be unaffected, because you are simply replacing the value of $h1{c} .另一方面,如果您使用$h1{c} = { } ,则原始%h2将不受影响,因为您只是替换了$h1{c}的值。 It was originally a reference to %h2 ;它最初是对%h2的引用; now it's a reference to a new anonymous hash.现在它是对新匿名哈希的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM