Maintainer: Adriano Ferreira <ferreira@cpan.org> Date: 14 Dec 2007 Last Modified: 14 Dec 2007 Number: 8 Version: 1
Status: Unfinished
Among the new Perl 6 operators, there is the handy
operator '//', known as defined-or or the default
operator. This novelty was anticipated by the introduction
of this syntactic bit in Perl 5 (see the upcoming
5.10 release) — so you won't
need to wait for Perl 6 to start using it.
# dor.pl use 5.010; print "arg: '", shift // "?", "'\n"; $ perl dor.pl one arg: 'one' $ perl dor.pl "" arg: '' $ perl dor.pl arg: '?'
The purpose of this operator is very close to the
well-known high-precedence OR, the operator '||',
with some subtle and useful differences.
Expressions with '||' are evaluated like this:
exp1 || exp2 = exp1, if the result of exp1 is true exp1 || exp2 = exp2, otherwise
It was very common to use this operator when one wanted an expression to have a certain default value if something was not explicitly specified.
For instance, the following Perl 5 code can build a rule of
length $n with a given char or '-'.
sub rule {
my $n = shift;
my $char = shift || '-';
return $char x $n;
}
Then
rule(3) gives '---' rule(4, '+') gives '++++'
But
rule(5, 0) gives '-----' (and not '00000')
because 0 is false (as the other Perl values
of falsehood: '' – the empty string, 0
– integer zero, 0.0 – floating
point zero, undef).
The solution was to replace the simple expression
shift || '-' by another one, more complex and precise:
my $char = defined $_[0] ? shift : '-';
But that is the semantics of the '//' operator:
exp1 // exp2 = exp1, if the result of exp1 is defined exp1 // exp2 = exp2, otherwise
So since 5.10, you may use the exact same code above
replacing '||' with '//' and keep your code
compact and elegant.
To be really fair, the Perl 6 rephrasing of this code
won't need the '//' operator. Instead, that sub would be even
prettier due to the improved sub signatures that
become possible.
sub rule ( $n, $char = '-' ) {
return $char x $n;
}
$Revision: 85 $