Best way to give a variable a default value (simulate Perl ||, ||= )

后端 未结 8 1385
眼角桃花
眼角桃花 2020-12-07 11:46

I love doing this sort of thing in Perl: $foo = $bar || $baz to assign $baz to $foo if $bar is empty or undefined. You al

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-07 12:15

    I think in general doing something like this:

    $foo = $bar || $baz;
    

    is a bad idea, unless $bar and $baz are both booleans. If they arent:

    $bar = 10;
    $baz = 11;
    

    then the question becomes: what determines if something is true or false? Most people would probably expect zero to be false, and everything else to be true. But with some languages (for example Ruby), only false and nil are false, which means both 0 and 1 would be true. Because of this cross language ambiguity, I think it best to be explicit in these cases:

    if ($bar !== 0) {
       $foo = $bar;
    } else {
       $foo = $baz;
    }
    

    or:

    $foo = $bar !== 0 ? $bar : $baz;
    

提交回复
热议问题