Assigning using ternary operator?

后端 未结 7 862
猫巷女王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:38

    You have a precedence problem. What you have is the same as

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

    You could make it work with parens.

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

    But it's much cleaner to move the assignment out.

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

    Moving along, there's no point in checking if the value is defined at all. Seeing as the only two possible values are undef and the string 1, a simple truth test would do.

    my $review = $model->test ? '1' : '';
    

    In fact, since you want true values unchanged, you could simply use the following

    my $review = $model->test || '';
    

    Finally, do you really need to change undef into to an empty string? If not, you can simply use the following:

    my $review = $model->test;
    

提交回复
热议问题