In Variables§
See primary documentation in context for The $ 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.
raku -ne 'say ++$ ~ " $_"' example.txt
Each reference to $
within a lexical scope is in effect a separate variable.
raku -e '{ say ++$; say $++ } for ^5' # OUTPUT: «1021324354»
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: «135»
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: «012» for ^3 { state $ = .say } # OUTPUT: «0»