Variables

Variables in Perl 6

Variable names start with a special character called a sigil, followed optionally by a second special character named twigil and then an identifier.

Sigils

The sigil serves as a variable indicator and type constraint.

Sigil Type constraint Default type Assignment Examples
$ Mu (no type constraint) Any item Int, Str, Array, Hash
@ Positional Array list List, Array, Range, Buf
% Associative Hash list Hash, Map, Pair
& Callable Callable item Sub, Method, Block, Routine

Examples:

my $square = 9 ** 2;
my @array  = 1, 2, 3;   # Array variable with three elements
my %hash   = London => 'UK', Berlin => 'Germany';

Variables without sigils are also possible, see sigilless variables.

Item and List Assignment

There are two types of assignment, item assignment and list assignment. Both use the equal sign = as operator. The distinction whether an = means item or list assignment is based on the syntax of the left-hand side.

Item assignment places the value from the right-hand side into the variable (container) on the left.

List assignment leaves the choice of what to do to the variable on the left.

For example, Array variables (@ sigil) empty themselves on list assignment and then put all the values from the right-hand side into themselves.

The type of assignment (item or list) is decided by the first context seen in the current expression or declarator:

my $foo = 5;            # item assignment
say $foo.perl;          # 5

my @bar = 7, 9;         # list assignment
say @bar.WHAT;          # Array
say @bar.perl;          # [7, 9]<>

(my $baz) = 11, 13;     # list assignment
say $baz.WHAT;          # (List)
say $baz.perl;          # (11, 13)

Thus, the behavior of an assignment contained within a list assignment depends on the expression or declarator that contains it.

For instance, if the internal assignment is a declarator, item assignment is used, which has tighter precedence than both the comma and the list assignment:

my @array;
@array = my $num = 42, "str";   # item assignment: uses declarator
say @array.perl;                # [42, "str"]<> (an Array)
say $num.perl;                  # 42 (a Num)

Similarly, if the internal assignment is an expression that is being used as an initializer for a declarator, the context of the internal expression determines the type of assignment:

my $num;
my @array = $num = 42, "str";    # item assignment: uses expression
say @array.perl;                 # [42, "str"]<> (an Array)
say $num.perl;                   # 42 (a Num)

my ( @foo, $bar );
@foo = ($bar) = 42, "str";       # list assignment: uses parens
say @foo.perl;                   # [42, "str"]<> (an Array)
say $bar.perl;                   # $(42, "str")  (a List)

However, if the internal assignment is neither a declarator nor an expression, but is part of a larger expression, the context of the larger expression determines the type of assignment:

my ( @array, $num );
@array = $num = 42, "str";    # list assignment
say @array.perl;              # [42, "str"]<> (an Array)
say $num.perl;                # [42, "str"]<> (an Array)

This is because the whole expression is @array = $num = 42, "str", while $num = 42 is not is own separate expression.

See operators for more details on precedence.

Sigilless variables

It is possible to create "variables" in Perl 6 that do not have sigils:

my \degrees = pi / 180;
my \θ       = 15 * degrees;

Note, however, that these do not create containers. That means degrees and θ above actually directly represent Nums. To illustrate, try assigning to one after you've defined it:

θ = 3; # Dies with the error "Cannot modify an immutable Num"

Sigilless variables do not enforce context, so they can be used to pass something on as-is:

sub logged(&f, |args) {
    say('Calling ' ~ &f.name ~ ' with arguments ' ~ args.perl)
    my \result = f(|args);
    #  ^^^^^^^ not enforcing any context here
    say(&f.name ~ ' returned ' ~ result.perl)
    return |result;
}

Twigils

Twigils influence the scoping of a variable. Please be aware that twigils have no influence over whether the primary sigil interpolates. That is, if $a interpolates, so do $^a, $*a, $=a, $?a, $.a, etc. It only depends on the $.

Twigil Scope
none Based only on declarator
* Dynamic
! Attribute (class member)
? Compile-time variable
. Method (not really a variable)
< Index into match object (not really a variable)
^ Self-declared formal positional parameter
: Self-declared formal named parameter
= Pod variables
~ The sublanguage seen by the parser at this lexical spot

The * Twigil

Dynamic variables are looked up through the caller, not through the outer scope. For example:

my $lexical   = 1;
my $*dynamic1 = 10;
my $*dynamic2 = 100;

sub say-all() {
    say "$lexical, $*dynamic1, $*dynamic2";
}

# prints 1, 10, 100
say-all();

{
    my $lexical   = 2;
    my $*dynamic1 = 11;
    $*dynamic2    = 101;

    # prints 1, 11, 101
    say-all();
}

# prints 1, 10, 101
say-all();

The first time &say-all is called, it prints "1, 10, 100" just as one would expect. The second time though, it prints "1, 11, 101". This is because $lexical isn't looked up in the caller's scope but in the scope &say-all was defined in. The two dynamic variables are looked up in the caller's scope and therefore have the values 11 and 101. The third time &say-all is called $*dynamic1 isn't 11 anymore, but $*dynamic2 is still 101. This stems from the fact that we declared a new dynamic variable $*dynamic1 in the block and did not assign to the old variable as we did with $*dynamic2.

The dynamic variables differ from other variable types in that referring to an undeclared dynamic variable is not a compile time error but a runtime failure, so a dynamic variable can be used undeclared as long as it is checked for definedness or used in a boolean context before using it for anything else:

sub foo() {
    $*FOO // 'foo';
}

say foo; # -> 'foo'

my $*FOO = 'bar';

say foo; # -> 'bar'

The ! Twigil

Attributes are variables that exist per instance of a class. They may be directly accessed from within the class via !:

class Point {
    has $.x;
    has $.y;

    method Str() {
        "($!x, $!y)"
    }
}

Note how the attributes are declared as $.x and $.y but are still accessed via $!x and $!y. This is because in Perl 6 all attributes are private and can be directly accessed within the class by using $!attribute-name. Perl 6 may automatically generate accessor methods for you though. For more details on objects, classes and their attributes see object orientation.

The ? Twigil

Compile-time variables may be addressed via the ? twigil. They are known to the compiler and may not be modified after being compiled in. A popular example for this is:

say "$?FILE: $?LINE"; # prints "hello.pl: 23" if this is the 23 line of a
                      # file named "hello.pl".

Although they may not be changed at runtime, the user is allowed to (re)define such variables.

constant $?TABSTOP = 4; # this causes leading tabs in a heredoc or in a POD
                        # block's virtual margin to be counted as 4 spaces.

For a list of these special variables see compile-time variables.

The . Twigil

The . twigil isn't really for variables at all. In fact, something along the lines of

class Point {
    has $.x;
    has $.y;

    method Str() {
        "($.x, $.y)" # note that we use the . instead of ! this time
    }
}

just calls the methods x and y on self, which are automatically generated for you because you used the . twigil when the attributes were declared. Note, however, that subclasses may override those methods. If you don't want this to happen, use $!x and $!y instead.

The fact that the . twigil just does a method call also implies that the following is possible too:

class SaySomething {
    method a() { say "a"; }
    method b() { $.a; }
}

SaySomething.b; # prints "a"

For more details on objects, classes and their attributes and methods see object orientation.

The < Twigil

The < twigil is just an alias for $/<...> where $/ is the match variable. For more information about the match variable see $/ and type Match.

The ^ Twigil

The ^ twigil declares a formal positional parameter to blocks or subroutines. Variables of the form $^variable are a type of placeholder variable. They may be used in bare blocks to declare formal parameters to that block. So the block in the code

    for ^4 {
        say "$^b follows $^a";
    }

which prints

1 follows 0
3 follows 2

has two formal parameters, namely $a and $b. Note that even though $^b appears before $^a in the code, $^a is still the first formal parameter to that block. This is because the placeholder variables are sorted in Unicode order. If you have self-declared a parameter using $^a once, you may refer to it using only $a thereafter.

Although it is possible to use nearly any valid identifier as a placeholder variable, it's recommended to use short names or ones that can be trivially understood in the correct order, to avoid surprise on behalf of the reader.

Subroutines may also make use of placeholder variables but only if they do not have an explicit parameter list. This is true for normal blocks too.

sub say-it    { say $^a; } # valid
sub say-it()  { say $^a; } # invalid
              { say $^a; } # valid
-> $x, $y, $x { say $^a; } # invalid

Placeholder variables syntactically cannot have any type constraints. Be also aware that one cannot have placeholder variables with a single upper-case letter. This is disallowed in favor of being to able to catch some Perl 5-isms.

The : Twigil

The : twigil declares a formal named parameter to a block or subroutine. Variables declared using this form are a type of placeholder variable too. Therefore the same things that apply to variables declared using the ^ twigil also apply here (with the exception that they are not positional and therefore not ordered using Unicode order, of course). So this:

    say { $:add ?? $^a + $^b !! $^a - $^b }( 4, 5 ) :!add

Will print "-1".

See ^ for more details about placeholder variables.

The = Twigil

The = twigil is used to access Pod variables. Every Pod block in the current file can be accessed via a Pod object, such as $=data, $=SYNOPSIS or =UserBlock. That is: a variable with the same name of the desired block and a = twigil.

=begin Foo
...
=end Foo

#after that, $=Foo gives you all Foo-Pod-blocks

You may access the Pod tree which contains all Pod structures as a hierarchical data structure through $=pod.

Note that all those $=someBlockName support the Positional and the Associative roles.

The ~ Twigil

Note: Slangs are NYI in Rakudo.

The ~ twigil is for referring to sublanguages (called slangs). The following are useful:

$~MAIN       the current main language (e.g. Perl statements)
$~Quote      the current root of quoting language
$~Quasi      the current root of quasiquoting language
$~Regex      the current root of regex language
$~Trans      the current root of transliteration language
$~P5Regex    the current root of the Perl 5 regex language

You may supersede or augment these languages in your current lexical scope by using

augment slang Regex {  # derive from $~Regex and then modify $~Regex
    token backslash:std<\Y> { YY };
}

or

supersede slang Regex { # completely substitute $~Regex
    ...
}

Variable Declarators and Scope

Most of the time it's enough to create a new variable using the my keyword:

    my $amazing-variable = "World";
    say "Hello $amazing-variable!"; # Hello World!

However, there are many declarators that change the details of scoping beyond what Twigils can do.

Declarator Effect
my Introduces lexically scoped names
our Introduces package-scoped names
has Introduces attribute names
anon Introduces names that are private to the construct
state Introduces lexically scoped but persistent names
augment Adds definitions to an existing name
supersede Replaces definitions of an existing name

There are also two prefixes that resemble declarators but act on predefined variables:

Prefix Effect
temp Restores a variable's value at the end of scope
let Restores a variable's value at the end of scope if the block exits unsuccessfully

The my Declarator

Declaring a variable with my gives it lexical scope. This means it only exists within the current block. For example:

{
    my $foo = "bar";
    say $foo; # -> "bar"
}
say $foo; # !!! "Variable '$foo' is not declared"

This dies because $foo is only defined as long as we are in the same scope.

Additionally, lexical scoping means that variables can be temporarily redefined in a new scope:

my $location = "outside";

sub outer-location {
    # Not redefined:
    say $location;
}

outer-location; # -> "outside"

sub in-building {
    my $location = "inside";
    say $location;
}

in-building; # -> "inside"

outer-location; # -> "outside"

If a variable has been redefined, any code that referenced the outer variable will continue to reference the outer variable. So here, &outer-location still prints the outer $location:

sub new-location {
    my $location = "nowhere"
    outer-location;
}

new-location; # -> "outside"

To make new-location() print nowhere, make $location a dynamic variable using the * twigil.

my is the default scope for subroutines, so my sub x() {} and sub x() {} do exactly the same thing.

The our Declarator

our variables work just like my variables, except that they also introduce an alias into the symbol table.

module M {
    our $Var;
    # $Var available here
}

# Available as $M::Var here.

The has Declarator

has scopes attributes to instances of a class or role, and methods to classes or roles. has is implied for methods, so has method x() {} and method x() {} do the same thing.

See object orientation for more documentation and some examples.

The anon Declarator

The anon declarator prevents a symbol from getting installed in the lexical scope, the method table and everywhere else.

For example you can use it to declare subroutines which know their own name, but still aren't installed in a scope:

my %operations =
    half   => anon sub half($x) { $x / 2 },
    square => anon sub square($x) { $x * $x },
    ;
say %operations<square>.name;       # square
say %operations<square>(8);         # 64

The state Declarator

state declares lexically scoped variables, just like my. However, initialization happens exactly once the first time the initialization is encountered in the normal flow of execution. Thus, state variables will retain their value across multiple executions of the enclosing block or routine.

Therefore, the subroutine

sub a {
    state @x;
    state $l = 'A';
    @x.push($l++);
};

say a for 1..6;

This works per "clone" of the containing code object, so:

    ({ state $i = 1; $i++.say; } xx 3).map: {$_(), $_()}; # says 1 then 2 thrice

Note that this is B<not> a thread-safe construct when the same clone of the same
block is run by multiple threads.  Also remember that methods only have one
clone per class, not per object.

will continue to increment $l and append it to @x each time it is called. So it will output

[A]
[A B]
[A B C]
[A B C D]
[A B C D E]
[A B C D E F]

As with my, declaring multiple state variables must be placed in parentheses and for declaring a single variable, parentheses may be omitted.

Please note that many operators come with implicit binding, what will lead to actions at a distance. Use .clone or coercion to create a new container that can be bound to.

my @a;
sub f () { 
	state $i;
	$i++;
	@a.push: "k$i" => $i # <-- .clone goes here
};
f for 1..3; 
dd @a; # «Array $var = $[:k1(3), :k2(3), :k3(3)]»

The $ Variable

As well as explicitly declared named state variables $ can be used as an anonymous state variable without an explicit state declaration:

perl6 -e 'sub foo() { say ++$  }; foo() for ^3'

produces:

1
2
3

Furthermore, state variables are not required to exist in 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 in effect is a separate variable, as illustrated by:

perl6 -e '{ say ++$; say $++  } for ^5'

which produces:

1
0
2
1
3
2
4
3
5
4

If you need to refer to the value of $ more than once within the scope it should be copied to a new variable, for example:

sub foo() {
    given ++$ {
        when 1 {
            say "one";
        }
        when 2 {
            say "two";
        }
        when 3 {
            say "three";
        }
        default {
            say "many";
        }
    }
}

foo() for ^3;

produces:

one
two
three

The @ Variable

In a similar manner to the $ variable there is also a Positional anonymous state variable @ :

sub foo($x) {
    say (@).push($x);
}

foo($_) for ^3;

Produces:

[0]
[0 1]
[0 1 2]

The @ here is parenthesized in order to disambiguate the expression from a class member variable named @.push. Indexed access doesn't require this disambiguation but you will need to copy the value in order to do anything useful with it:

sub foo($x) {
    my $v = @;
    $v[$x] = $x;
    say $v;
}

foo($_) for ^3;

Produces:

[0]
[0 1]
[0 1 2]

As with $ each mention of @ in a scope introduces a new anonymous array.

The % Variable

Finally there is also an Associative anonymous state variable %:

sub foo($x) {
    say (%).push($x => $x);
}

foo($_) for ^3;

Which produces:

0 => 0
0 => 0, 1 => 1
0 => 0, 1 => 1, 2 => 2

The same caveat about disambiguation applies. As you may expect, indexed access is also possible (with copying to make it useful):

sub foo($x) {
    my $v = %;
    $v{$x} = $x;
    say $v;
}

foo($_) for ^3;

Which produces:

0 => 0
0 => 0, 1 => 1
0 => 0, 1 => 1, 2 => 2

As with the other anonymous state variables each mention of % within a given scope will effectively introduce a separate variable.

The augment Declarator

With augment, you can add attributes and methods to existing classes and grammars, provided you activated the MONKEY-TYPING pragma first.

Since classes are usually our scoped, and thus global, this means modifying global state, which is strongly discouraged. For almost all situations, there are better solutions.

# don't do this
use MONKEY-TYPING;
augment class Int {
    method is-answer { self == 42 }
}
say 42.is-answer;       # True

(In this case, the better solution would be to use a function).

The supersede Declarator

The temp Prefix

Like my, temp restores the old value of a variable at the end of its scope. However, temp does not create a new variable.

my $in = 0; # temp will "entangle" the global variable with the call stack
            # that keeps the calls at the bottom in order.
sub f(*@c) { 
    (temp $in)++;
     "<f>\n"
     ~ @c>>.indent($in).join("\n")
     ~ (+@c ?? "\n" !! "")
     ~ '</f>'
}; 
sub g(*@c) { 
    (temp $in)++;
    "<g>\n" 
    ~ @c>>.indent($in).join("\n")
    ~ (+@c ?? "\n" !! "")
    ~ "</g>"
}; 
print g(g(f(g()),g(),f()));

output:

<g>
 <g>
  <f>
   <g>
   </g>
  </f>
  <g>
  </g>
  <f>
  </f>
 </g>
</g>

The let Prefix

Restores the previous value if the block exits unsuccessfully. A successful exit means the block returned a defined value or a list.

my $answer = 42;

{
    let $answer = 84;
    die if not Bool.pick;
    CATCH {
        default { say "it's been reset :(" }
    }
    say "we made it 84 sticks!";
}

say $answer;

In the above case, if the Bool.pick returns true, the answer will stay as 84 because the block returns a defined value (say returns true). Otherwise the die statement will cause the block to exit unsuccessfully, resetting the answer to 42.

Type Constraints and Initialization

Variables can have a type constraint, which goes between the declarator and the variable name:

    my Int $x = 42;
    $x = 'a string';    # throws an X::TypeCheck::Assignment error

If a scalar variable has a type constraint but no initial value, it is initialized with the type object of the constraint type.

my Int $x;
say $x.^name;       # Int
say $x.defined;     # False

Scalar variables without an explicit type constraint are typed as Mu but default to the Any type object.

Variables with the @ sigil are initialized with an empty Array; variables with the % sigil are initialized with an empty Hash.

The default value of a variable can be set with the is default trait, and re-applied by assigning Nil to it:

my Real $product is default(1);
say $product;                       # 1
$produce *= 5;
say $product;                       # 5
$product = Nil;
say $product;                       # 1

Special Variables

Perl 5 is infamous for its many obscure special variables. Perl 6 also has special variables but only has three that are extra short due to how often they're used. Other special variables have longer, more descriptive names.

Pre-defined lexical variables

There are three special variables that are available in every block:

Variable Meaning
$_ topic variable
$/ regex match
$! exceptions

The $_ Variable

$_ is the topic variable. It is the default parameter for blocks that do not have an explicit signature, so constructs like for @array { ... } and given $var { ... } bind to $_ simply by invoking the block.

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

CATCH blocks set $_ to the exception that was caught. The ~~ smart-match operator sets $_ 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>/;
}

This outputs:

Looking for strings with non-alphabetic characters...
ab:c
d$e
ij*

The $/ Variable

$/ is the match variable. It stores the result of the last Regex match and so usually contains objects of type Match.

'abc 12' ~~ /\w+/;  # sets $/ to a Match object
say $/.Str;         # abc

The Grammar.parse method also sets the caller's $/ to the resulting Match object.

use XML;
XML.parse(slurp "filename.xml")
say $/;

Positional Attributes

$/ can have positional attributes if the Regex had capture-groups in it, which are just formed with parentheses.

'abbbbbcdddddeffg' ~~ / a (b+) c (d+ef+) g /;
say $/[0]; # 「bbbbb」
say $/[1]; # 「dddddeff」

These can also be accessed by the shortcuts $0, $1, $2, etc.

say $0; # 「bbbbb」
say $1; # 「dddddeff」

To get all of the positional attributes, any of $/.list, @$/, or @() can be used.

say @().join; # bbbbbdddddeff

Named Attributes

$/ can have named attributes if the Regex had named capture-groups in it, or if the Regex called out to another Regex.

'I.... see?' ~~ / \w+ $<punctuation>=[ <-[\w\s]>+ ] \s* $<final-word> = [ \w+ . ] /;
say $/<punctuation>; # 「....」
say $/<final-word>;  # 「see?」

These can also be accessed by the shortcut $<named>.

say $<punctuation>; # 「....」
say $<final-word>;  # 「see?」

To get all of the named attributes, any of $/.hash, %$/, or %() can be used.

say %().join;       # "punctuation     ....final-word  see?"

The $! Variable

$! is the error variable. If a try block or statement prefix catches an exception, that exception is stored in $!. If no exception was caught, $! is set to the Any type object.

Note that CATCH blocks do not set $!. Rather they set $_ inside the block to the caught exception.

Compile-time variables

$?FILE Which file am I in?
$?LINE Which line am I at?
::?CLASS Which class am I in?
&?ROUTINE Which routine am I in?
&?BLOCK Which block am I in?
%?LANG What is the current set of interwoven languages?
%?RESOURCES The files associated with the "Distribution" of the current compilation unit.

Other compile-time variables:

$?SCOPE Which lexical scope am I in?
$?PACKAGE Which package am I in?
$?MODULE Which module am I in?
$?CLASS Which class am I in? (as variable)
$?ROLE Which role am I in? (as variable)
$?GRAMMAR Which grammar am I in?
$?TABSTOP How many spaces is a tab in a heredoc or virtual margin?
$?USAGE The usage message generated from the signatures of MAIN subs.
$?ENC Default encoding of Str.encode/Buf.decode/various IO methods.

Dynamic variables

$*ARGFILES Magic command-line input handle.
@*ARGS Arguments from the command line.
$*IN Standard input filehandle, AKA stdin
$*OUT Standard output filehandle, AKA stdout
$*ERR Standard error filehandle, AKA stderr
%*ENV Environment variables
$*REPO A variable holding information about modules installed/loaded
$*TZ The system's local timezone.
$*CWD The Current Working Directory.
$*KERNEL Which kernel am I running under?
$*DISTRO Which OS distribution am I running under?
$*VM Which virtual machine am I running under?
$*PERL Which Perl am I running under?
$*PID Process ID of the current process.
$*PROGRAM-NAME Path to the current executable as it was entered on the command line, or C<-e> if perl was invoked with the -e flag.
$*PROGRAM Location (in the form of an C<IO::Path> object) of the Perl program being executed.
$*EXECUTABLE Absolute path of the perl executable that is currently running.
$*EXECUTABLE-NAME The name of the perl executable that is currently running. (e.g. perl6-p, perl6-m, Niecza.exe) Favor $*EXECUTABLE because it is not guaranteed that the perl executable is in PATH.
$*USER The user that is running the program. It is an object that evaluates to "username (uid)". It will evaluate to the username only if treated as a string and the numeric user id if treated as a number.
$*GROUP The primary group of the user who is running the program. It is an object that evaluates to "groupname (gid)". It will evaluate to the groupname only if treated as a string and the numeric group id if treated as a number.
$*HOME An L<IO::Path> object representing the "home directory" of the user that is running the program. If the "home directory" cannot be determined it will be L<Nil>
$*SPEC The appropriate L<IO::Spec> sub-class for the platform that the program is running on.
$*TMPDIR An L<IO::Path> object representing the "system temporary directory"
$*THREAD A L<Thread> object representing the currently executing thread.
$*SCHEDULER A L<ThreadPoolScheduler> object representing the current default scheduler.