简体   繁体   English

Perl参考哈希切片

[英]perl reference hash slice

I have below hash: 我下面有哈希:

my %gilligan_info = (
        name            =>      'Gilligan',
        hat             =>      'white',
        shirt           =>      'Red',
        position        =>      'First Mate',
);

my %skipper_info = (
        name            =>      'Skipper',
        hat             =>      'Black',
        shirt           =>      'Blue',
        position        =>      'Captain'
);

I have a array of hashes: 我有一系列哈希:

my @crew = (\%gilligan_info, \%skipper_info);

I created a reference: 我创建了一个参考:

my $ref = \%{$crew[1]};

I'm pulling key values from second hash: 我从第二个哈希中提取键值:

my @ref_values = @{$ref}{ qw ( name position hat )};

My question is, how can I get values of hashes by not specifying element number in reference "$ref"? 我的问题是,如何通过在引用“ $ ref”中未指定元素编号来获取哈希值?

Thanks 谢谢

如果您希望单个数组中所有哈希的值,

my @ref_values = map @$_{ qw(name position hat) }, @crew;

I think what you want is for @ref_values to contain an array of values for each of the @crew . 我认为您想要的是让@ref_values包含每个@crew的值数组。

Something like this, perhaps 大概是这样

my @ref_values;

for my $crew ( @crew ) {
  push @ref_values, [ @$crew{ qw(name position hat) } ];
}

This is also possible using map if you prefer, similarly to the solution from Сухой27 如果愿意,也可以使用map ,类似于Сухой27的解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM