cr8ivecodesmith
cr8ivecodesmith

Reputation: 2061

Hashes array elements copy

My array of hashes:

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

Expected result:

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

Any simple way to get only the values of the first hash element from
this and assign it to an array?

Upvotes: 3

Views: 214

Answers (3)

daxim
daxim

Reputation: 39158

Mind that hashes are unordered, so I take the word first to mean lexicographically 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 (???)
}

The expression returns qw(9872 9871).

Assigning an arrayref to an array as in @cur = […] is probably a mistake, but I took it at face value.


Bonus perl5i solution:

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

The expression returns the same values as above. This code is a bit longer, but IMO more readable because the flow of execution goes strictly from top to bottom, from left to right.

Upvotes: 8

Alex Reynolds
Alex Reynolds

Reputation: 96986

use Data::Dumper;
my @hashes = map (@{$_}, map ($_, $cur[0]));
my @result = map ($_->{'A'} , @hashes);    
print Dumper \@result;

Upvotes: 1

Toto
Toto

Reputation: 91518

First your array have to be defined as

my @cur = (
    {
        'A' => '9872',
        'B' => '1111'
    },
    {
        'A' => '9871',
        'B' => '1111'
    }
);

Note the parenthesis

#!/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;

Upvotes: 3

Related Questions