Reputation: 2277
I have an array of Hashes with the following structure:
@fields
(
{
"id" => "Name",
"type" => "Text",
"value" = undef,
},
{
"id" => "DOB",
"type" => "Date",
"value" = undef,
},
);
and I have an array with the following elements:
@data = ("John", "10/10/1970");
What wold be the best way to copy the elements of the @data
to @fields
to get the following without having to iterate and use array indices.
@fields
(
{
"id" => "Name",
"type" => "Text",
"value" = "John",
},
{
"id" => "DOB",
"type" => "Date",
"value" = "10/10/1970",
},
);
Upvotes: 1
Views: 100
Reputation:
Perhaps you should make @fields
into a hash instead, which would allow you to easily retrieve a field by name.
use warnings;
use strict;
my %fields =
(
Name => {
type => "Text",
value => undef,
},
DOB => {
type => "Date",
value => undef,
},
);
my @data = ("John", "10/10/1970");
$fields{Name}->{value} = $data[0];
$fields{DOB}->{value} = $data[1];
use Data::Dumper;
print Dumper %fields;
Upvotes: 3
Reputation: 37146
A hash slice would have worked if this was within a single hash reference. However, since you have to populate a specific field across multiple hash references, a loop will be needed.
use List::Util 'min';
$fields[$_]->{value} = $data[$_] for 0 .. min( $#fields, $#data );
Upvotes: 3