复制哈希数组元素



我的哈希数组:

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

预期结果:

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

仅从
获取第一个哈希元素的值的任何简单方法然后把它赋值给数组?

请注意,散列是无序的,所以我把first这个词表示在字典顺序上是第一个

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 = […]中那样将arrayref赋值给数组可能是一个错误,但我从表面上看它。


奖金perl5i解决方案:

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

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

首先你的数组必须被定义为

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;
use Data::Dumper;
my @hashes = map (@{$_}, map ($_, $cur[0]));
my @result = map ($_->{'A'} , @hashes);    
print Dumper @result;

最新更新