Regex 如何将不同的键映射到同一个值,但只声明一次?
是否可以将不同的键映射到哈希中的同一个值,但只使用一个插槽? 例如,如果我有以下信息:Regex 如何将不同的键映射到同一个值,但只声明一次?,regex,perl,hash,scripting,Regex,Perl,Hash,Scripting,是否可以将不同的键映射到哈希中的同一个值,但只使用一个插槽? 例如,如果我有以下信息: my %hash = ( person => A, persons => A, employee => C, employees => C, desk => X, ); 我能不能把它做成: my %hash = ( person|persons => A, employee|employees
my %hash = (
person => A,
persons => A,
employee => C,
employees => C,
desk => X,
);
我能不能把它做成:
my %hash = (
person|persons => A,
employee|employees => C,
desk => X,
);
有可能吗?没有类似的内置语法。但你总是可以做到:
my %hash;
$hash{employee} = $hash{employees} = 'C';
甚至:
my %hash;
@hash{qw( employee employees )} = ('C') x 2; # or ('C', 'C'); or qw(C C);
没有任何类似的内置语法。但你总是可以做到:
my %hash;
$hash{employee} = $hash{employees} = 'C';
甚至:
my %hash;
@hash{qw( employee employees )} = ('C') x 2; # or ('C', 'C'); or qw(C C);
我不清楚你的目标,但也许是一个问题 如果使用中间别名哈希,则可以使用 然后通过%categories访问值,以达到%hash中的值
my %categories = (
person => people,
persons => people,
employee => worker,
employees => worker,
desk => furniture,
chair => furniture,
);
my %hash = (
people => A,
worker => C,
furniture => X,
);
我不清楚你的目标,但也许是一个问题 如果使用中间别名哈希,则可以使用 然后通过%categories访问值,以达到%hash中的值
my %categories = (
person => people,
persons => people,
employee => worker,
employees => worker,
desk => furniture,
chair => furniture,
);
my %hash = (
people => A,
worker => C,
furniture => X,
);
没有内置语法,但您可以使用一个小助手函数:
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',
);
没有内置语法,但您可以使用一个小助手函数:
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',
);
有一个类似的问题和解决方案,IMO的最佳解决方案如下:
my %hash = map { my $item = pop @$_; map { $_, $item } @$_ }
[qw(HELP ?) => sub { ... }],
[qw(QUIT EXIT LEAVE) => sub { ... }],
...;
有一个类似的问题和解决方案,IMO的最佳解决方案如下:
my %hash = map { my $item = pop @$_; map { $_, $item } @$_ }
[qw(HELP ?) => sub { ... }],
[qw(QUIT EXIT LEAVE) => sub { ... }],
...;
这当然是可能的;如果引用正确,第二个代码段将编译。如果您解释为什么要这样做,您可能会得到更好的解决方案。@ThisSuitesBlack它不会运行,但不会给出所需的结果。至少,据我所知不是这样。@ThisSuitesBlackNot:为什么?但是为了能够在出现键入错误时灵活地使用键,避免出现带有使用警告的键入错误?你甚至可以。不清楚你说的一个插槽是什么意思。如果一个改变了,你想两个都改变吗?这当然是可能的;如果引用正确,第二个代码段将编译。如果您解释为什么要这样做,您可能会得到更好的解决方案。@ThisSuitesBlack它不会运行,但不会给出所需的结果。至少,据我所知不是这样。@ThisSuitesBlackNot:为什么?但是为了能够在出现键入错误时灵活地使用键,避免出现带有使用警告的键入错误?你甚至可以。不清楚你说的一个插槽是什么意思。如果其中一个发生变化,您是否希望两个都发生变化?被否决的投票人是否愿意发表评论?我想知道原因。落选的选民想评论一下吗?我想知道原因。