【问题标题】:Print a Perl hash of hashes打印散列的 Perl 散列
【发布时间】:2019-01-13 04:20:37
【问题描述】:

我正在构建一个哈希值。如何使用while 获取每个值?

my %users = ();

while ( my $row_ref = $select_sth->fetchrow_hashref() ) {

    $id     = $row_ref->{uid};
    $name   = $row_ref->{name};
    my $loc = $row_ref->{loc };

    $users{$loc}{$name} = $id;
}

while ( my ($user, $val) = each(%users) ) {

    # how to get name, loc, id?

    my $uname = ??
    my $uloc  = ??
    my $uid   = ??
}

【问题讨论】:

  • 为什么你声明了my $loc而不是$id$name

标签: arrays perl hash dbi


【解决方案1】:

在嵌套循环中遍历哈希的两个级别。

for my $loc (keys %users) {
    for my $name (keys $users{$loc}->%*) {
        say "loc: $loc -- name: $name -- id: $users{$loc}{$name}";
    }
}

提示:使用Data::Dumper 或类似方法可视化嵌套数据结构。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-30
    • 2017-08-22
    • 2011-03-13
    • 2014-12-14
    • 2013-03-14
    • 1970-01-01
    • 2012-08-03
    • 2010-11-12
    相关资源
    最近更新 更多