Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

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 quite deep and the code is not very readable. Is there a more concise way to do the above assignments?

like image 939
gogators Avatar asked Aug 20 '15 16:08

gogators


People also ask

How do you assign default values to variables?

The OR Assignment (||=) Operator The logical OR assignment ( ||= ) operator assigns the new values only if the left operand is falsy. Below is an example of using ||= on a variable holding undefined . Next is an example of assigning a new value on a variable containing an empty string.

What is the default value of object variable * undefined?

undefined is a type by itself (undefined). Unassigned variables are initialized by JavaScript with a default value of undefined. Here as the variable is declared but not assigned to any value, the variable by default is assigned a value of undefined. On the other hand, null is an object.

What is the default value of a variable in Python?

Python has a different way of representing syntax and default values for function arguments. Default values indicate that the function argument will take that value if no argument value is passed during the function call. The default value is assigned by using the assignment(=) operator of the form keywordname=value.

What is the default value of object variable?

In Java, the default value of any object is null.


1 Answers

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;
like image 75
Andy Lester Avatar answered Sep 22 '22 12:09

Andy Lester