Documentation for 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␤» 

If you need to use the value of $ more than once in a scope, it should be copied to a new variable.

sub foo() {
    given ++$ {
        when 1 {
            say "one";
        }
        when 2 {
            say "two";
        }
        when 3 {
            say "three";
        }
        default {
            say "many";
        }
    }
}
 
foo() for ^3;
# OUTPUT: «one␤two␤three␤» 

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.

subset DynInt where $ = ::('Int'); # the initializer will be called for each type check 
subset DynInt where state $ = ::('Int'); # the initializer is called once, this is a proper cache