How to check if a value and return value are defined or some default value

In my code, I often write things like this:

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

or

 my $b = exists $hash{$_} ? $hash{$_} : $default_value; 

Sometimes the hash is pretty deep and the code is not very readable. Is there a shorter way to complete the above tasks?

+5
source share
1 answer

Assuming you are using Perl 5.10 and higher, 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 am checking for defined $hash{$_} , not exists $hash{$_} , like you do. There is no abbreviation for existence, nor for definition.

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

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

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

 $a = $x unless $x; # Checks for truth, not definedness. $a ||= $x; 
+12
source

All Articles