2014-01-28 61 views
2

是否有可能将不同的键映射到散列中的相同值,但只使用1个“槽”?
例如如果我有以下几点:如何将不同的键映射到相同的值,但只声明一次?

my %hash = ( 
    person => A, 
    persons => A, 
    employee => C, 
    employees => C, 
    desk => X, 
); 

我能获得某种希望:

my %hash = ( 
    person|persons => A, 
    employee|employees => C, 
    desk => X, 
); 

这可能吗?

+0

它当然有可能;如果引用正确,你的第二个代码片段将被编译。但是,如果你解释为什么你想这样做,你可能会得到更好的解决方案。 – ThisSuitIsBlackNot

+0

@ThisSuitIsBlack不会运行,但不会产生预期的结果。至少,不是我所能说的。 – terdon

+0

@ThisSuitIsBlackNot:为什么?但是为了能够在键入错误的情况下允许灵活的使用 – Jim

回答

2

这里没有任何内建的语法。但是,你总是可以做:

my %hash; 
$hash{employee} = $hash{employees} = 'C'; 

甚至:

my %hash; 
@hash{qw(employee employees)} = ('C') x 2; # or ('C', 'C'); or qw(C C); 
+0

+ 1.第二种解决方案似乎对我来说是不可读的BTW – Jim

+0

下来的选民是否会评论?我想知道原因。 – Qtax

0

你的目标是我不清楚,但是,也许一的形式给出 在您使用中间的“别名”哈希会工作。

然后通过%类别访问值达到%的散列值

my %categories = ( 
person => people, 
persons => people, 
employee => worker, 
employees => worker, 
desk => furniture, 
chair => furniture, 
); 

my %hash = ( 
    people => A, 
    worker => C, 
    furniture => X, 
); 
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', 
); 
1

有一个类似的问题和解决方案posted over on perlmonks whe (IMO)最好的解决方案是这样的:

my %hash = map { my $item = pop @$_; map { $_, $item } @$_ } 
[qw(HELP ?) => sub { ... }], 
[qw(QUIT EXIT LEAVE) => sub { ... }], 
...; 
相关问题