Defined - or operator "//"
Starting with Perl 5.10, the very useful Defined-or operator " // " has been introduced. An operator followed by two slashes. It's very difficult to search, so it's a good idea to remember it early. In recent years, it's the most recommended function for me.
# Defined-or operator // //
The Defined-or operator returns the lvalue if the lvalue is defined, and returns the rvalue if it is undefined.
# The right side is substituted my $value = undef //'default'; # 'default' # The left side is substituted my $value = 0 //'default'; # 0 my $value = '' //'default'; # '''' my $value = 'foo' //'default'; # 'foo'
This is very useful for defining a default value if no value is given.
my $name = $opts{name} //'Ken';
You can also write //= .
$value //='default';
Only if $value is undefined will $value be assigned'default'.
What did you do before Perl 5.10
Previously, in order to do this, you had to use defined function to write:
$value = 'default' unless defined $value;
Also, since this writing method is verbose, many people used the || operator to write as follows.
$value ||='default';
However, this way of writing introduced a potential bug to the application because'default' was assigned even if $value was 0 or an empty string.
With the introduction of the Defined-or operator, I'm happy that I don't have to worry about the description between the above two.