在Perl中的push中使用条件运算符
我是 Perl 开发的新手,我想检查是否允许在 push 语句中使用条件运算符。像这样的东西
push(@myMap, {
key1 => value1,
key2 => value2,
(condition)?{
key3 => value3,
}:(),
key4 => value4
});
基本上我只想根据条件向地图添加一个值
回答
是的,但你的代码是错误的。
push(@myMap, {
key1 => value1,
key2 => value2,
(condition) ?
{ ### these brackets are wrong
key3 => value3,
} ###
:(),
key4 => value4
});
如果条件为真,则您正在创建具有奇数个元素的数据结构。它将包含单个哈希引用作为值之一,因此您不再拥有键/值对,并且它可能会抱怨。
它会尝试做你想做的事,基本上把那个哈希引用转换成它的字符串表示,然后key4用作值,让你留下value4和undef作为最后一对。
使固定:
push(@myMap, {
key1 => value1,
key2 => value2,
(condition) ? ( key3 => value3 ) : (),
key4 => value4
});
- @simbabque, I'm not a big fan of it, but it's is a known idiom. That makes it defacto readable if the pattern can be recognized, and this one is easy to recognize. It's like I instantly know that we're doing something with duplicate if I see `!$seen{$_}++` near a `grep` or `if`. It's not cause I spent time parsing the expression; it's that it's a familiar pattern.