variable $

Documentation for variable $ assembled from the following types:

declarator state

From state

(state) variable $

In addition to explicitly declared named state variables, $ can be used as an anonymous state variable without an explicit state declaration.

say "1-a 2-b 3-c".subst(:g, /\d/{<one two three>[$++]});
# OUTPUT: «one-a two-b three-c␤» 

Furthermore, state variables can be used outside of subroutines. You could, for example, use $ in a one-liner to number the lines in a file.

perl6 -ne 'say ++$ ~ " $_"' example.txt

Each reference to $ within a lexical scope is in effect a separate variable.

perl6 -e '{ say ++$; say $++  } for ^5'
# OUTPUT: «1␤0␤2␤1␤3␤2␤4␤3␤5␤4␤» 

That is why, if you need to reference the same $ variable (or, for that matter, any of the other anon state variables @ and %) more than once, a possible solution is to bind another variable to it, although in this example it would be more straightforward to just declare state $x and not use the magical/anonymous $ variable:

sub foo () {
    my $x := $;
    $x++;
    say $x;
    $x = $x + 1;
}
 
foo() for ^3# OUTPUT: «1␤3␤5␤» 

In general, it is better style to declare a named state variable in case you have to refer to it several times.

Note that the implicit state declarator is only applied to the variable itself, not the expression that may contain an initializer. If the initializer has to be called exactly once, the state declarator has to be provided.

for ^3 {       $ = .say } # OUTPUT: «0␤1␤2␤» 
for ^3 { state $ = .say } # OUTPUT: «0␤»