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

mam*_*aye 2 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' } 
];
Run Code Online (Sandbox Code Playgroud)

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

cho*_*oba 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";
Run Code Online (Sandbox Code Playgroud)

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

my @friend_ids = map $_->{id}, @friends;
Run Code Online (Sandbox Code Playgroud)

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

my @friend_ids = sort {$a <=> $b} uniq map $_->{id}, @friends;
Run Code Online (Sandbox Code Playgroud)

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

my @friend_ids = sort uniq map $_->{id}, @friends;
Run Code Online (Sandbox Code Playgroud)

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

  • push方法是:«push @friend_ids,$ _-> {id} for @friends;`»或«`push map $ _-> {id},@ friend_ids;`».没理由同时使用`map`和`for`. (2认同)
  • @mamesaye:如果引用保存在标量中,只需使用`@ $ ref`取消引用它.如果你真的使用数组来保持引用,引用将保存在它的第0个成员`$ array [0]`中,所以使用`@ {$ array [0]}`来取消引用它. (2认同)