【问题标题】:Hash of hash is lost when it is out of a subroutine出子程序时散列的散列丢失
【发布时间】:2020-04-06 20:47:14
【问题描述】:

我遇到了哈希哈希的问题。我想从 foreach 循环创建散列散列。我希望我可以在 foreach 循环之外使用 hash 的哈希值。但是,在 foreach 循环内,散列的哈希值看起来不错,但在循环外却不行。我的代码如下。

my(%pother,%pget);

foreach $stn (@stns){
       if (($stn eq 'A')||($stn eq 'B')) {
              &getSomething($stn,\%pother);  #getSomething is a subroutine and it outputs a hash
       }

       $pget{$stn} = \%pother;  # I would like to create a hash of hash

       print map { "$_ => $pget{$stn}{$_}\n" } keys %{$pget{$stn}};  # My 1st print result, which looks good
}

print map { "$_ => $pget{'A'}{$_}\n" } keys %{$pget{'A'}}; # My 2nd print result, which is same as my 3rd one 

print map { "$_ => $pget{'B'}{$_}\n" } keys %{$pget{'B'}}; # My 3rd print result, which is same as my 2nd one

%pother 的哈希值是这样的。 %pother 的输出将取决于 $stn

%pother = (
    '20200406' => 82,
    '20200405' => 99,
);

我想像这样创建一个哈希值:

$pget = {
          'A' => {
                          '20200406' => 82,
                          '20200405' => 99,
                        },
          'B' => {
                         '20200406' => 97,
                         '20200405' => 67,
                       }
        };

但是,我得到的是如下:

$pget = {
          'A' => {
                          '20200406' => 97,
                          '20200405' => 67,
                        },
          'B' => {
                         '20200406' => 97,
                         '20200405' => 67,
                       }
        };

我不知道为什么当 hash 的散列在 foreach 循环之外时“A”和“B”变得相同。

谢谢!

【问题讨论】:

    标签: perl hash


    【解决方案1】:

    你实际上有以下几点:

    my %pother;  # Create a hash.
    # ...
    $pget{A} = \%pother;
    # ...
    $pget{B} = \%pother;
    # ...
    

    那么为什么你会认为$pget{A}$pget{B} 会有所不同呢?

    my %pother; 移动到循环中,以在每次循环通过时创建一个新的哈希。

    【讨论】:

      猜你喜欢
      • 2015-01-26
      • 2013-08-04
      • 2014-05-19
      • 2010-09-26
      • 2011-07-08
      • 1970-01-01
      • 2012-07-22
      • 2013-03-15
      • 2018-07-20
      相关资源
      最近更新 更多