3 ms·
> You shouldn't encourage the use of 'value || defaultValue' without clearly, explicitly pointing out that this will prevent the use of falsy values as argument
by kbenson 14y ago
> You shouldn't encourage the use of 'value || defaultValue' without clearly, explicitly pointing out that this will prevent the use of falsy values as argument values - including 0, false, and an empty string... all values people actually want to use in some cases.
Perl dealt with this a few versions back, and now they have an operator for "defined-or", // [1]. It's useful.
This makes it easier to correct the wrong (but common) way to supply default values for undefined/unpassed values:
# Old wrong way
my $foo = $bar || $baz; # $this will never be used if "falsy": 0, '', undef, '0E0'
# Old right ways
my $foo = defined $bar ? $bar : $baz;
# Or
my $foo = $bar;
$foo = $baz unless defined $foo;
# New way
my $foo = $bar // $baz; # Uses $baz only if not defined $bar
[1]: http://perldoc.perl.org/perlop.html#Logical-Defined-Or