Course of Raku / Essentials / Scalar variables

The defined-or operator

Use the so-called defined-or operator // to get a fallback value if a variable is not yet set.

my $a = 'alpha';
say $a // 'gamma';

my $b;
say $b // 'delta';

This program prints:

alpha
delta

The value of $a is set in the first line, so in the expression $a // 'gamma', the current value of $a is used. In contrast, the $b variable was not initialised, so $b // 'delta' returns the right-hand-side operand, and the program prints delta.

//=

The combination of // and = gives the //= operator that assigns a value if the variable is not defined.

my $x;
$x //= 42;
say $x; # 42

Course navigation

Scalar variables / Declaration with initialization   |   Scalar variables / Names of the variables


💪 Or jump directly to the exercises to this section.