2012-01-02 67 views
3

我的哈希值的数组:哈希数组元素复制

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

预期结果:

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

任何简单的方法来从
此获得第一个哈希元素的唯一值,并将其分配给数组?

回答

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; 
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 = […]那样指定一个arrayref作为数组可能是一个错误,但我将它作为面值。


加成perl5i溶液:

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

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