How to test if defined and return value or some default value

后端 未结 1 1257
囚心锁ツ
囚心锁ツ 2021-01-19 02:06

In my code, I often write things like this:

my $a = defined $scalar ? $scalar : $default_value;

or

my $b = exists $hash{$_}         


        
相关标签:
1条回答
  • 2021-01-19 02:38

    Assuming you're using Perl 5.10 and above, you can use the // operator.

    my $a = defined $x ? $x : $default;  # clunky way
    my $a = $x // $default;              # nice way
    

    Similarly you can do

    my $b = defined $hash{$_} ? $hash{$_} : $default;  # clunky
    my $b = $hash{$_} // $default;                     # nice
    

    Note that in my example above I'm checking defined $hash{$_}, not exists $hash{$_} like you had. There's no shorthand for existence like there is for definedness.

    Finally, you have the //= operator, so you can do;

    $a = $x unless defined $a;  # clunky
    $a //= $x;                  # nice
    

    This is analogous to the ||= which does the same for truth:

    $a = $x unless $x;  # Checks for truth, not definedness.
    $a ||= $x;
    
    0 讨论(0)
提交回复
热议问题