哈希数组元素复制

cr8*_*ith 3 arrays perl copy elements

我的哈希数组:

@cur = [
          {
            'A' => '9872',
            'B' => '1111'
          },
          {
            'A' => '9871',
            'B' => '1111'
          }
        ];
Run Code Online (Sandbox Code Playgroud)

预期结果:

@curnew = ('9872', '9871');
Run Code Online (Sandbox Code Playgroud)

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

dax*_*xim 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 (???)
}
Run Code Online (Sandbox Code Playgroud)

表达式返回qw(9872 9871).

将arrayref分配给数组@cur = […]可能是一个错误,但我从表面上看它.


Bonus perl5i解决方案:

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

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