【问题标题】:"Can't use string ("") as a HASH ref while "strict refs" in use at" error while assigning hash to an hash in perl“在将哈希分配给 perl 中的哈希时,“不能使用字符串 (””) 作为哈希引用,而“严格引用”在使用时出现错误
【发布时间】:2021-09-23 22:45:44
【问题描述】:

我将一个哈希 %attributes 分配给另一个哈希 %attributes_r。我需要将其打印为该哈希 %attributes 的键/值对,如下所述。但是,在打印时,为什么我会收到这个错误,“Can't use string ("") as a HASH ref while "strict refs" in use at" in this line "foreach my $key1 (keys %{$attributes_r{ $key}}) {" ?

我的代码:

use strict;
use warnings;
our %attributes_r;
my %attributes = ('clear'      => 0,
               'reset'      => 0,
               'bold'       => 1,
               'dark'       => 2,
               'underscore' => 4,
               'blink'      => 5,
               'reverse'    => 7,
               'concealed'  => 8
               );


for (keys %attributes) {
    $attributes_r{$attributes{$_}} = $attributes{$_};
    # print "$_ => $attributes_r{$attributes{$_}}\n";
}


foreach my $key (keys %attributes_r)    {
    foreach my $key1 (keys %{$attributes_r{$key}})    {
        print "$key1 = > $attributes_r{$key}{$key1}\n";
    }
}

感谢任何帮助。

【问题讨论】:

  • $_ 是关键,所以$attributes_r{$attributes{$_}} = $attributes{$_}; 应该是$attributes_r{$_} = $attributes{$_};。也许你应该给循环变量一个名字以避免混淆... /// 第二个循环没有意义。
  • 您能否编辑问题以显示您希望新的$attributes_r 看起来像什么?我的意思是,尽可能准确地展示它——理想情况下,你会向我们展示该哈希应该是什么。

标签: html xml perl


【解决方案1】:

根据您的数据,这是不正确的:

    foreach my $key1 (keys %{$attributes_r{$key}})  {

您正在尝试取消引用一个字符串值,而不是引用,就像错误所说的那样。如果您确实有哈希哈希,它可能会起作用,但您没有。

您可能正在尝试创建哈希哈希,我不确定。这段代码很奇怪:

$attributes_r{$attributes{$_}} = $attributes{$_};   

在这里,您从原始散列中获取值并将其用作另一个散列中的键。例如:

$attributes_r{0} = 0;

这并不能真正完成任何有用的事情。如果您澄清您正在尝试做什么,我可能会提出修复建议。

另外,如果您想查看您正在创建的数据结构,我建议您使用Data::Dumper 打印它,如下所示:

use Data::Dumper;
...
print Dumper \%attributes_r;

【讨论】:

  • 我想将%attributes hash的键值对赋值给%attributes_r hash
  • 如何在“ $attributes_r{0} = 0; ”中将此 %attributes 哈希的键/值转换为 %attributes_r 哈希
  • 如果要复制哈希,只需复制哈希:%attributes_r = %attributes。或遍历键/值:for my $key (keys %a) { $a_r{$key} = $a{$key} }。请注意,这仅适用于简单结构。
  • 我不想复制它。我想将此哈希分配为另一个哈希的键。 (即)像这样的东西:$a_r{$a}{$key}
  • 在我看来,您需要研究有关数据结构的 Perl 文档,然后再提出一个新问题。
猜你喜欢
  • 2019-06-11
  • 2014-07-27
  • 2017-12-20
  • 2014-03-31
  • 2017-01-06
  • 2018-04-06
  • 1970-01-01
  • 2011-12-19
  • 1970-01-01
相关资源
最近更新 更多