哈希数组元素复制

时间:2012-01-02 10:35:35

标签: arrays perl copy elements

我的哈希数组:

@cur = [
          {
            'A' => '9872',
            'B' => '1111'
          },
          {
            'A' => '9871',
            'B' => '1111'
          }
        ];

预期结果:

@curnew = ('9872', '9871');

从中获取第一个哈希元素的值的任何简单方法 这并将其分配给一个数组?

3 个答案:

答案 0 :(得分:8)

请注意哈希是无序的,所以我先用这个词来表示首字母词汇

map {                               # iterate over the list of hashrefs
    $_->{                           # access the value of the hashref
        (sort keys $_)[0]           # … whose key is the first one when sorted
    }
}
@{                                  # deref the arrayref into a list of hashrefs
    $cur[0]                         # first/only arrayref (???)
}

表达式返回qw(9872 9871)

@cur = […]中一样将数组引用分配给数组可能是一个错误,但我把它看作是面值。


Bonus perl5i解决方案:

use perl5i::2;
$cur[0]->map(sub {
    $_->{ $_->keys->sort->at(0) } 
})->flatten;

表达式返回与上面相同的值。这段代码有点长,但IMO更具可读性,因为执行流程从上到下,从左到右严格执行。

答案 1 :(得分:3)

首先,您的数组必须定义为

my @cur = (
    {
        'A' => '9872',
        'B' => '1111'
    },
    {
        'A' => '9871',
        'B' => '1111'
    }
);

注意括号

#!/usr/bin/perl 
use strict;
use warnings;
use Data::Dump qw(dump);

my @cur = (
    {
        'A' => '9872',
        'B' => '1111'
    },
    {
        'A' => '9871',
        'B' => '1111'
    }
);
my @new;
foreach(@cur){
    push @new, $_->{A};
}
dump @new;

答案 2 :(得分:1)

use Data::Dumper;
my @hashes = map (@{$_}, map ($_, $cur[0]));
my @result = map ($_->{'A'} , @hashes);    
print Dumper \@result;
相关问题