Assigning using ternary operator?

后端 未结 7 857
猫巷女王i
猫巷女王i 2021-02-01 03:56

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 = \'\'
}
         


        
7条回答
  •  盖世英雄少女心
    2021-02-01 04:58

    First of all, "That didn't work either" is not the most helpful thing you could tell us. It's important to know exactly how it didn't work: what did it do, what did you expect, and how to they differ?

    But the problem with

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

    is operator precedence. The conditional operator ? : binds more tightly than the assignment operator =, so the above is equivalent to:

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

    So if $model->test is defined, it does the equivalent of

    $review = "1" = '';
    

    You can fix that problem with parentheses:

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

    But really, why would you want to? The conditional (ternary) operator is useful when you want to use the result. If the result is going to be discarded, as it is here, it's clearer (and, as you've seen, less error-prone) to use an if/else statement:

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

    or, if you insist on writing it on one line:

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

    If you really want to use a conditional expression, you can do this:

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

    which is probably a reasonable way to do it.

    BUT :

    The defined operator itself yields either "1" (true) or "" (false). so the whole thing can be reduced to:

    $review = defined($model->test);
    

提交回复
热议问题