You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在嵌套数组与哈希结构中获取bar的邮箱(禁用硬编码索引)

如何从嵌套数组哈希结构中获取'bar'对应的邮箱地址

首先是你提供的数据结构:

my $data = [
          {
            'foo' => {
                       'lang' => 'en',
                       'contact' => [
                                      {
                                        'email' => 'foo@example.org'
                                      },
                                      {
                                        'phone' => '2125551212'
                                      }
                                    ],
                       'browser' => 'firefox'
                     }
          },
          {
            'bar' => {
                       'lang' => 'fr',
                       'contact' => [
                                      {
                                        'email' => 'bar@example.com'
                                      },
                                      {
                                        'phone' => '9125551212'
                                      }
                                    ],
                       'browser' => 'lynx'
                     }
          }
        ];

由于不能硬编码数组索引,需要逐层遍历筛选,以下是两种可行方案:

方案一:显式循环(可读性优先)

这种写法逻辑清晰,适合复杂嵌套结构的调试和维护:

my $bar_email;

# 遍历外层数组的每个哈希项
foreach my $item (@$data) {
    # 找到包含'bar'键的条目
    next unless exists $item->{bar};
    
    # 遍历contact数组提取邮箱
    foreach my $contact_entry (@{$item->{bar}{contact}}) {
        if (exists $contact_entry->{email}) {
            $bar_email = $contact_entry->{email};
            last; # 找到邮箱后终止内层循环
        }
    }
    last; # 找到bar条目后终止外层循环
}

# 输出结果
print $bar_email if defined $bar_email; # 输出: bar@example.com

方案二:函数式写法(简洁优先)

利用Perl的grep和map组合,用链式操作完成筛选:

my ($bar_email) = map {
    map { $_->{email} } grep { exists $_->{email} } @{$_->{bar}{contact}}
} grep { exists $_->{bar} } @$data;

print $bar_email if defined $bar_email;

核心要点

  • 用exists检查键的存在性,避免因键缺失触发警告或错误
  • 外层遍历不依赖固定数组索引,自动适配数组中新增的元素
  • 内层遍历contact数组,兼容联系方式顺序变化的情况

内容的提问来源于stack exchange,提问作者Frank Dawns

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 22:42:22