哈希数组元素复制

3

我的哈希数组:

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

预期结果:

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

有没有简单的方法获取第一个哈希元素的值,并将其赋值给一个数组?
3个回答

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 = […]可能是一个错误,但我按字面意思理解了它。


奖励perl5i解决方案:

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

这个表达式返回与上面相同的值。虽然代码有点长,但我认为更易读,因为执行流程严格从上到下、从左到右。


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;

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接