是否可以将不同的键映射到散列中的相同值,但只使用1“插槽”? 例如。如果我有以下内容:
my %hash = (
person => A,
persons => A,
employee => C,
employees => C,
desk => X,
);
我可以这样做:
my %hash = (
person|persons => A,
employee|employees => C,
desk => X,
);
有可能吗?
答案 0 :(得分:2)
没有任何类似的内置语法。但你可以随时做:
my %hash;
$hash{employee} = $hash{employees} = 'C';
甚至:
my %hash;
@hash{qw( employee employees )} = ('C') x 2; # or ('C', 'C'); or qw(C C);
答案 1 :(得分:1)
没有内置语法,但你可以使用一个小辅助函数:
sub make_hash {
my @result;
while (my ($key, $value) = splice @_, 0, 2) {
push @result, $_, $value for split /\|/, $key;
}
return @result;
}
然后你可以说:
my %hash = make_hash(
'person|persons' => 'A',
'employee|employees' => 'C',
desk => 'X',
);
答案 2 :(得分:1)
有一个类似的问题和解决方案posted over on perlmonks其中(IMO)最佳解决方案是这样的:
my %hash = map { my $item = pop @$_; map { $_, $item } @$_ }
[qw(HELP ?) => sub { ... }],
[qw(QUIT EXIT LEAVE) => sub { ... }],
...;
答案 3 :(得分:0)
我的目标不明确,但也许是一种方法 你使用中间“别名”哈希的地方就可以了。
然后通过%类别访问值以达到%hash
中的值my %categories = (
person => people,
persons => people,
employee => worker,
employees => worker,
desk => furniture,
chair => furniture,
);
my %hash = (
people => A,
worker => C,
furniture => X,
);