=begin pod

=TITLE Perl 6 variables

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

=head1 Sigils

The sigil serves both as rough type constraint, and as an indicator
as to whether the contents of the variable flatten in list context. See also
the documentation in L<List>.

=begin table

    Sigil   Type constraint          Default type  Flattens  Assignment
    =====   ===============          ============  ========  ==========
    $       Mu (no type constraint)  Any           No        item
    &       Callable                 Callable      No        item
    @       Positional               Array         Yes       list
    %       Associative              Hash          Yes       list

=end table

Examples:

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

There are two types of assignment, I<item assignment> and I<list assignment>.
Both use the equal sign C<=> as operator. The distinction whether an C<=>
means item or list assignment is based on the syntax of the left-hand side.
(TODO: explain in detail, or do that in L<operators>).

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 L<Array> variables (C<@> sigil) empty themselves on list assignment,
and then put all the values from the right-hand side into themselves. Contrary
to item assignment, it means that the type of the variable on the left always
stays C<Array>, regardless of the type of the right-hand side.

Note that the item assignment has tighter precedence than list assignment, and
also tighter than the comma. See L<operators> for more details.

=head1 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 C<$a>
interpolates, so do C<$^a>, C<$*a>, C<$=a>, C<$?a>, C<$.a>, etc.  It only
depends on the $.

=begin table

    Twigil  Scope
    ======  =====
    *       dynamic
    !       attribute (class member)
    ?       compile-time "constant"
    .       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

=end table

=head2 C<*>

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

=begin code
    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();
=end code

The first time C<&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
C<$lexical> isn't looked up in the caller's scope but in the scope C<&say-all>
was defined in. The two dynamic variables are looked up in the callers scope and
therefore have the values 11 and 101. The third time C<&say-all> is called
C<$*dynamic1> isn't 11 anymore, but C<$*dynamic2> is still 101. This stems from
the fact that we declared a new dynamic variable C<$*dynamic1> in the block and
did not assign to the old variable as we did with C<$*dynamic2>.

=head2 C<!>

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

=begin code
    class Point {
        has $.x;
        has $.y;

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

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

=head2 C<?>

Compile-time "constants" may be addressed via the C<?> 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 constants.

    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 those special variables see L<Compile-time "constants">.

=head2 C<.>

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

=begin code
    class Point {
        has $.x;
        has $.y;

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

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

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

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

    SaySomething.a; # prints "a"
=end code

For more details on objects, classes and their attributes and methods see
L<objects>.

=head2 <

The C<< < >> twigil is just an alias for C<< $/<...> >> where C<$/> is the match
variable. For more information on the match variable see L<$/>.

=head2 C<^>

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

    for ^4 {
        say "$^seconds follows $^first";
    }

which prints

    1 follows 0
    3 follows 2

has two formal parameters, namely C<$first> and C<$second>. Note that even
though C<$^second> appears before C<$^first> in the code, C<$^first> 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 C<$^a> once you may refer to it using only C<$a> thereafter.

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 can not have placeholder variables with a single upper-case
letter. This is disallowed in favor of being to able to catch some Perl 5-isms.

=head2 C<:>

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

See L<^> for more details about placeholder variables.

=head2 C<=>

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

    =begin code
    =begin Foo
    ...
    =end Foo

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

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

Note that all those C<$=someBlockName> support the C<Positional> and the
C<Associative> role.

=head2 C<~>

The C<~> 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 C<supersede> or C<augment> those languages in your current lexical scope
by doing

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

or

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

=head1 Special Variables

=head2 Often-Used Variables

# TODO: find a better heading

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

=begin table

    Variable    Meaning

    $_          topic variable
    $/          regex match
    $!          exceptions

=end table

=head3 C<$_>

C<$_> is the topic variable. It is the default parameter for blocks that do
not have an explicit signature, so constructs like C<for @array { ... }>
and C<given $var { ... }> binds to C<$_> 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

C<CATCH> blocks set C<$_> to the exception that was caught. The C<~~>
smart-match operator sets C<$_> on the right-hand side expression to the
value of the left-hand side.

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

    .say;                   # same as $_.say

C<m/regex/> and C</regex/> regex matches and C<s/regex/subst/> substitutions
work on C<$_>.

=head3 C<$/>

C<$/> is the match variable. It stores the result of each regex match, and
usually contains objects of type L<Match>.

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

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

Other match variables are aliases to elements of C<$/>:

    $0          # same as $/[0]
    $1          # same as $/[1]
    $<named>    # same as $/<named>

=head3 C<$!>

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

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

=head2 Compile-time "constants"

    $?FILE      Which file am I in?
    $?LINE      Which line am I at?
    &?ROUTINE   Which routine am I in?
    &?BLOCK     Which block am I in?
    %?LANG      What is the current set of interwoven languages?

Other compile-time constants:

    $?KERNEL    Which kernel am I compiled for?
    $?DISTRO    Which OS distribution am I compiling under
    $?VM        Which virtual machine am I compiling under
    $?XVM       Which virtual machine am I cross-compiling for
    $?PERL      Which Perl am I compiled for?
    $?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.

=head2 Dynamic variables

    $*ARGFILES  Magic command-line input handle.
    @*ARGS      Arguments from the command line.
    $*IN        Standard input filehandle.
    $*OUT       Standard output filehandle.
    $*ERR       Standard error filehandle.
    $*TZ        The system's local timezone.
    $*CWD       The Current Working Directory.

=head2 Other variables

    $*PROGRAM_NAME     Path to the current executable as it was typed in on the
                       command line, or C<-e> if perl was invoked with the -e flag.
    $*PID              Process ID of the current process.
    $*OS               Which Operating System am I compiling under (e.g. Linux).
    $*OSVER            Version of the current Operating System.
    $*EXECUTABLE_NAME  The name of the perl executable that is currently running.

=end pod
