【问题标题】:How to print hash of hash in where one hash is reference to other如何在一个哈希引用另一个哈希的地方打印哈希的哈希
【发布时间】:2014-03-30 06:47:19
【问题描述】:

我正在尝试在 perl 中学习复杂的数据结构,为此我编写了代码但没有得到任何输出:

#!/usr/bin/perl 
use strict;
use warnings;

my %abc=(Education => "BE",Marital_Status => "Single", Age => "28", Working_Exp => "4yrs");
my %cde=(Education => "BE",Marital_Status => "Single", Age => "29", Working_Exp => "5yrs");


my %info =(info_one => "\%abc", info_two => "\%cde");

foreach my $val (keys %info)
{
  foreach my $check ( keys %{$info{val}})
  {
    print ${$info{val}}{check}."\n";
  }
}

【问题讨论】:

  • 使用有助于存储和管理数据的匿名哈希。
  • @NaghaveerRGowda:您的意思是,使用“hashrefs”,并且您希望比说“将帮助您存储和管理数据”更准确:)
  • @DanDascalescu:是的,它的“hashrefs”,谢谢 Dan :)

标签: perl


【解决方案1】:

对于在 Perl 中学习复杂的数据结构,没有比 Perl Data Structures Cookbook 更好的参考了。

info_oneinfo_two are 字符串的赋值,所以你想删除 \%abc\%cde 周围的双引号。此外,您需要将$ 标量符号添加到最后print 行中的valcheck,因为它们是变量。

#!/usr/bin/perl 
use strict;
use warnings;

my %abc= (
    Education => "BE",
    Marital_Status => "Single", 
    Age => "28", 
    Working_Exp => "4yrs"
);
my %cde= (
    Education => "BE",
    Marital_Status => "Single", 
    Age => "29", 
    Working_Exp => "5yrs"
);


my %info = (
   info_one => \%abc,
   info_two => \%cde
);

foreach my $val (keys %info) {
    foreach my $check ( keys %{$info{$val}} ) {
        print ${$info{$val}}{$check}."\n";
    }
}

最后一行有点难看,但是当您阅读 Data Structures Cookbook 时,您将学会使用 -> 运算符并更优雅地编写语句。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    • 2022-12-10
    • 2020-02-20
    相关资源
    最近更新 更多