【问题标题】:How do you get nested key value of a hash in Perl?如何在 Perl 中获取哈希的嵌套键值?
【发布时间】:2014-10-17 11:10:31
【问题描述】:

我想遍历哈希引用并获取键(如果存在),但我想要的键位于哈希引用的第二级。我希望能够为拥有它的散列引用的所有第一级键获取此键

例子:

    my $total = 0;
    foreach my $student (keys $students) {
        if ( exists $student->{???}->{points} ) {
            $total += $student->{points};
        }
    }
    return $total;

我遇到的问题是我想“不在乎”$student->{???} 的值是什么,只是想为它找到{points}

【问题讨论】:

  • 为什么要结束这个问题,这不是调试,而是要理解 perl 中的哈希循环。
  • 只遍历二级哈希有什么问题?
  • 为什么不:if ( exists $students->{$student}->{points} ) {
  • foreach my $student (keys %{$students}){
  • 因为键 %$students 如果你有一个 hashref 而不是 hash...

标签: perl hash


【解决方案1】:

您将$students 变量与$student 变量混为一谈:

    if ( exists $student->{???}->{points} ) {
                ^^^^^^^^
                Should be $students

但是,如果您不关心第一级 HoH 的 keys,那么就不要对它们进行迭代。

只需迭代 values 即可:

use strict;
use warnings;

use List::Util qw(sum);

my $students = {
    bob => { points => 17 },
    amy => { points => 12 },
    foo => { info   => 'none' },
    bar => { points => 13 },
};

my $total = sum map { $_->{points} // 0 } values %$students;

print "$total is the answer\n";

输出:

42 is the answer

【讨论】:

  • 谢谢,我最终做了 foreach my $student (keys %$students) { if ( exists $students->{$student}->{points} ) {...} },如sum map() 现在超出了我的范围。将尝试对此进行重构,因为它是单线。也感谢您指出我使用 $student 的错误,现在我明白了如何使用散列遍历循环
猜你喜欢
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
  • 2011-02-14
  • 1970-01-01
  • 1970-01-01
  • 2013-02-12
  • 2015-01-10
相关资源
最近更新 更多