在Perl中,如何从hashrefs数组中提取ID字段列表?

时间:2012-05-10 18:59:49

标签: arrays perl hash

如何从哈希数组中推送数组中的每个id值?

我有这个数组:

@friends = [ 
   {'id' => 1, 'last_name' => 'Fo', 'first_name' => 'fa' }, 
   {'id' => 3, 'last_name' => 'pa', 'first_name' => 'pi' }, 
   {'id' => 2, 'last_name' => 'ma', 'first_name' => 'mi' } 
];

我想使用push创建一个像这样的值id数组:@friend_ids = [1, 3, 2]

2 个答案:

答案 0 :(得分:10)

您可能拥有@friends = ( ... )并希望@friend_ids = (1, 3, 2)。方括号用于数组引用,而不是列表。 您可以像这样创建这样的数组:

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

my @friends = ( {id => 1, last_name => 'Fo', first_name => 'fa' },
                {id => 3, last_name => 'pa', first_name => 'pi' },
                {id => 2, last_name => 'ma', first_name => 'mi' } );
my @friend_ids;
push @friend_ids, $_->{id} for @friends;
print "@friend_ids\n";

但是你可以更轻松地实现同样的目标:

my @friend_ids = map $_->{id}, @friends;

如果您需要删除重复项并对键进行排序,可以使用:

my @friend_ids = sort {$a <=> $b} uniq map $_->{id}, @friends;

如果所有ID都是数字或只是

my @friend_ids = sort uniq map $_->{id}, @friends;

如果某些ID不是数字(uniq来自List::MoreUtils)。

答案 1 :(得分:2)

我会使用散列,以便删除重复项并使结果易于排序(,如果需要):

my @friends = ( {id => 1, last_name => 'Fo', first_name => 'fa' },  
                {id => 3, last_name => 'pa', first_name => 'pi' },  
                {id => 2, last_name => 'ma', first_name => 'mi' } );  

my %id = map { $_->{id} => 1 } @friends;
my @friend_ids = sort { $a <=> $b } (keys %id); 
print "@friend_ids\n";

你可以test this script on Ideone