使用三元运算符分配? [英] Assigning using ternary operator?

查看:89
本文介绍了使用三元运算符分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Perl 5.8,需要分配默认值。我最终这样做:

I am on Perl 5.8 and am needing to assign a default value. I ended up doing this:

if ($model->test) {
    $review = "1"
} else {
    $review = ''
}

$ model-> test 的值将为 1 或未定义。如果 $ model-> test 中有内容,请将 $ review 设置为 1 否则将其设置为''

The value of $model->test is going to be either "1" or undefined. If there's something in $model->test, set $review to "1" otherwise set it equal to ''.

因为它不是Perl 5.10,我可以不要使用新的时髦的定义或运算符。我的第一个反应是使用像这样的三元运算符...

Because it's not Perl 5.10 I can't use the new swanky defined-or operator. My first reaction was to use the ternary operator like this...

defined($model->test) ? $review = "1" : $review = '';

但这也不起作用。

有人知道如何更有效地分配它吗?
Janie

Does anyone have an idea how to assign this more efficiently? Janie

推荐答案

我通常将其写为:

$review = ( defined($model->test) ? 1 : '' );

其中的括号是为了使其他阅读代码的人更清楚。

where the parentheses are for clarity for other people reading the code.

这篇关于使用三元运算符分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆