What is the most Pythonic way to provide a fall-back value in an assignment?

后端 未结 9 2276
暗喜
暗喜 2021-02-01 04:29

In Perl, it\'s often nice to be able to assign an object, but specify some fall-back value if the variable being assigned from is \'undef\'. For instance:

my $x         


        
9条回答
  •  忘了有多久
    2021-02-01 04:52

    Just some nitpicking with your Perl example:

    my $x = undef;
    

    This redundant code can be shortened to:

    my $x;
    

    And the following code doesn't do what you say it does:

    my $a = $x || $y;
    

    This actually assigns $y to $a when $x is false. False values include things like undef, zero, and the empty string. To only test for definedness, you could do the following (as of Perl 5.10):

    my $a = $x // $y;
    

提交回复
热议问题