Raku Books / Perl 6 at a Glance / Operators / Prefixes
?, so
? is a unary operator casting the context to a Boolean
one by calling the Bool method on an object.
say ?42; # TrueThe second form, so, is a unary operator with lower
precedence.
say so 42; # True
say so True; # True
say so 0.0; # FalseCodeBlockPlaceholder3raku my Str $a = ~42; say $a.WHAT; # (Str) CodeBlockPlaceholder4raku my $x = 41; say ++$x; # 42 CodeBlockPlaceholder5
CodeBlockPlaceholder6raku my $f = “file001.txt”;
++$f; say $f; # file002.txt
++$f; say $f; # file003.txt CodeBlockPlaceholder7raku my $x = 42; say –$x; # 41 CodeBlockPlaceholder8raku my $x = 10; my $y = +^$x; say $y; # -11 (but not -10) CodeBlockPlaceholder9
Compare this operator with the following one.
?^ is a logical negation operator. Please note that this
is not a bitwise negation. First, the argument is converted to a Boolean
value, and then the result is negated.
my $x = 10;
my $y = ?^$x;
say $y; # False
say $y.WHAT; # (Bool)CodeBlockPlaceholder11raku .print for ^5; # 01234 CodeBlockPlaceholder12
This code is equivalent to the following, where both ends of the range are explicitly specified:
.print for 0..4; # 01234| flattens the compound objects into a list. For
example, this operator should be used when you pass a list to a
subroutine, which expects a list of scalars:
sub sum($a, $b) {
$a + $b
}
my @data = (10, 20);
say sum(|@data); # 30Without the | operator, the compiler will report an
error, because the subroutine expects two scalars and cannot accept an
array as an argument:
Calling sum(Positional) will never work with declared signature ($a, $b)temp creates a temporary variable and restores its value
at the end of the scope (like it does the local built-in
operator in Perl 5).
my $x = 'x';
{
temp $x = 'y';
say $x; # y
}
say $x; # xCodeBlockPlaceholder17raku my $var = ‘a’; try { let $var = ‘b’; die; } say $var; # a ```
With a die, this example code will print the initial
value a. If you comment out the call of a die,
the effect of the assignment to b will stay, and the
variable will contain the value b after the
try block.
The let keyword looks similar to the declarators like
my and our, but it is a prefix operator.