KeyPi
KeyPi

Reputation: 526

Substituting array values into a hash

I would like to know if there's a way to make a substitution into an hash taking values from array. This is my exemple:

%h = (
"a" => 'one,two,three',
"b" => 'four,five,six'
);

@a = "a: Letter", "b: Letter", "one: 1", "two: 2", "three: 3", "four: 4", "five: 5", "six: 6";

Final hash should be:

%h2 = (
"a" => 'one: 1,two: 2,three: 3',
"b" => 'four: 4,five: 5,six: 6'
);

I've tried many ways in order to get it: substitution, put the elements into an array.. But then I lost the elements order so my result was:

@a2 = "a: Letter", "b: Letter", "one: 1", "two: 2", "three: 3", "four: 4", "five: 5", "six: 6";

Upvotes: 0

Views: 76

Answers (1)

Miller
Miller

Reputation: 35208

You just need to translate you @a array into a more useful form, such as a hash of key value pairs. Then you can process the values of %h to replace your words with more full information:

use strict;
use warnings;

my %h = (
    "a" => 'one,two,three',
    "b" => 'four,five,six',
);

my @a = ("a: Letter", "b: Letter", "one: 1", "two: 2", "three: 3", "four: 4", "five: 5", "six: 6");

# Translate @a into key value pairs for later substitution
my %a = map {
    my ($key) = split ':';
    ($key => $_);
} @a;

# Proces values of %h
for (values %h) {
    s/(\w+)/$a{$1} or warn "Unknown key $1"/eg;
}

use Data::Dump;
dd \%h;

Outputs:

{ a => "one: 1,two: 2,three: 3", b => "four: 4,five: 5,six: 6" }

If you want to process both of keys and values, work on the flattened form of the hash and reassign it:

%h = map {s/(\w+)/$a{$1}/eg; $_} %h;

Outputs:

{
  "a: Letter" => "one: 1,two: 2,three: 3",
  "b: Letter" => "four: 4,five: 5,six: 6",
}

Upvotes: 1

Related Questions