Name

Yet Another Perl 6 Operator: Boolean Operators

Version

Maintainer: Adriano Ferreira <ferreira@cpan.org>
Date: 29 Sep 2007
Last Modified: 12 Dec 2007
Number: 7
Version: 5
Status: Published

Body

In the article on coercion operators, we got to know the prefix operator '?' which converts values into Bool::True or Bool::False. Like it happens with '~' for strings, '?' is recurrent for boolean operators.

In Perl 6, the usual infix boolean operators are:

?& - and
?| - or
?^ - xor

These operators evaluate their operands in boolean context and apply simple Boole's algebra on them.

False ?& False  # False
''    ?& 'yes'  # False
1     ?& False  # False
42    ?& 42     # True

""    ?| 0      # False
False ?| True   # True
[1]   ?| 0      # True
True  ?| True   # True

''    ?^ ''     # False
undef ?^ {a=>1} # True
{:k}  ?^ undef  # True
True  ?^ True   # False

Each of the three operators always evaluate both sides and return one of the standard values Bool::True or Bool::False. So these boolean AND and OR do not short-circuit as their logical counterparts: '&&' and '||'. Precedence is different too.

            Equivalent to         precedence

$a ?& $b    ?$a * ?$b != 0        multiplicative
$a ?| $b    ?$a + ?$b != 0        additive
$a ?^ $b    ?$a + ?$b == 1        additive

The boolean negation operator may be written '?^' or '!'.

?^ $a       Equivalent to         True ?^  $a

Conceptually '?^' coerces to boolean first and then flips the bit. Synopsis 3 recommends the use of '!' instead.

See Also

Perl 6 coercion operators

$Revision: 84 $