在 Perl 中循环遍历哈希数组 [英] Looping through an array of hashes in Perl

查看:97
本文介绍了在 Perl 中循环遍历哈希数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全是 Perl 新手,所以如果这真的很愚蠢,请原谅我,但我无法弄清楚这一点.如果我有这样的数组:

I'm a total Perl newbie, so forgive me if this is really stupid, but I can't figure this out. If I have an array like this:

my @array = (
  {username => 'user1', email => 'user1@email' },
  {username => 'user2', email => 'user2@email' },
  {username => 'user2', email => 'user3@email' }
);

遍历这个数组最简单的方法是什么?我认为这样的事情会奏效:

What's the most simple way to loop through this array? I thought something like this would work:

print "$_{username} : $_{email}\n" foreach (@array);

但事实并非如此.我想我太沉迷于 PHP 思维方式了,我可以这样做:

But it doesn't. I guess I'm too stuck with a PHP mindset where I could just do something like:

foreach ($array as $user) { echo "$user['username'] : $user['email']\n"; }

推荐答案

@array包含hashreferences,所以需要使用->代码>取消引用.

@array contains hash references, so you need to use -> to derefecence.

print "$_->{username} : $_->{email}\n" foreach (@array);

另见文档,例如 perldoc perlreftutperldoc perlref.

See also the documentation, for instance perldoc perlreftut and perldoc perlref.

这篇关于在 Perl 中循环遍历哈希数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆