将数组值替换为哈希值

时间:2014-05-26 18:36:49

标签: perl hash

我想知道是否有一种方法可以从数组中取代哈希值。 这是我的例子:

%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";

最终哈希应该是:

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

为了得到它,我尝试了很多方法:替换,将元素放入数组中..但后来我丢失了元素顺序,所以我的结果是:

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

1 个答案:

答案 0 :(得分:1)

您只需将@a数组转换为更有用的形式,例如键值对的散列。然后,您可以处理%h的值,以使用更完整的信息替换您的字词:

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;

输出:

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

如果要处理键和值两者,请处理散列的展平形式并重新分配:

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

输出:

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