Sam Pinar
Sam Pinar

Reputation: 43

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"?

Thanks

Upvotes: 1

Views: 532

Answers (2)

Borodin
Borodin

Reputation: 126742

I think what you want is for @ref_values to contain an array of values for each of the @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

Upvotes: 0

mpapec
mpapec

Reputation: 50657

If you want values of all hashes in single array,

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

Upvotes: 1

Related Questions