$_
ErrorsCollection

$_

Synthesised documentation from language/variables

From language/variables

See Original text in context

$_ is the topic variable. A fresh one is created in every block. It's also the default parameter for blocks that do not have an explicit signature, so constructs like for @array { ... } and given $var { ... } bind the value or values of the variable to $_ by invoking the block.

for <a b c> { say $_ }  # binds $_ to 'a', 'b' and 'c' in turn 
say $_ for <a b c>;     # same, even though it's not a block 
given 'a'   { say $_ }  # binds $_ to 'a' 
say $_ given 'a';       # same, even though it's not a block

Because $_ is bound to the value of the iteration, you can also assign to $_ if it is bound to something assignable.

my @numbers = ^5;   # 0 through 4 
$_++ for @numbers;  # increment all elements of @numbers 
say @numbers;
 
# OUTPUT: «1 2 3 4 5␤»

CATCH blocks bind $_ to the exception that was caught. The ~~ smartmatch operator binds $_ on the right-hand side expression to the value of the left-hand side.

Calling a method on $_ can be shortened by leaving off the variable name:

.say;                   # same as $_.say

m/regex/ and /regex/ regex matches and s/regex/subst/ substitutions work on $_:

say "Looking for strings with non-alphabetic characters...";
for <ab:c d$e fgh ij*> {
    .say if m/<-alpha>/;
}
 
# OUTPUT: «Looking for strings with non-alphabetic characters... 
#          ab:c 
#          d$e 
#          ij*␤»