=begin pod :kind("Language") :subkind("Language") :category("migration")

=TITLE Perl to Raku guide - special variables

=SUBTITLE A comparison of special variables in Perl and Raku

=head1 DESCRIPTION

A (hopefully) comprehensive list of Perl Special Variables with their Raku
equivalents with notes on variations between them where necessary.

=head1 NOTE

This document is an attempt to guide the reader from the
I<Special Variables> in Perl to their equivalents in Raku.
For full documentation on the Raku I<Special Variables>,
please see the Raku documentation for each of them.


=head1 SPECIAL VARIABLES

X<|Special Variables (Perl)>

=head2 General variables

=head3 $ARG, $_

X<|$_ (Perl)>

Thankfully, C<$_> is the general default variable as in Perl. The
main difference in Raku is that you can now call methods on
it. For instance, Perl's C<say $_> can be rendered in Raku as
C<$_.say>. Furthermore, as it is the default variable, you don't even
need to use the variable name. The previous example can also be
achieved by using C<.say>.

=head3 @ARG, @_

X<|@_ (Perl)>

As Raku now has function signatures, your arguments can go there, rather
than depending on C<@_> for them. In fact, if you use a function signature, use
of C<@_> will spit at you telling it cannot override an existing signature.

If, however, you do not use a function signature, C<@_> will contain the
arguments you pass to the function as it did in Perl. Again, as with C<$_>,
you can call methods on it. Unlike C<$_> you cannot assume C<@_> as the
default variable for those methods to operate on (i. e. C<@_.shift> works,
C<.shift> does not).

=head3 $LIST_SEPARATOR, $"

Currently, there is no equivalent of the List Separator variable in Raku.
Design document L<S28|https://design.raku.org/S28.html> says there isn't one,
so you probably don't want to hold your breath.

=head3 $PROCESS_ID, $PID, $$

X<|$$ (Perl)>

C<$$> is replaced in Raku by C<$*PID>

=head3 $PROGRAM_NAME, $0

X<|$0 (Perl)>

You can access the program name in Raku via C<$*PROGRAM-NAME>.

Note: C<$0> in Raku is the variable holding the first captured value from a
regexp match (i. e. capture variables now start from C<$0> rather than C<$1>).

=head3 $REAL_GROUP_ID, $GID, $(

In Raku the group information is handled by C<$*GROUP>,
which holds an object of type L<IntStr|/type/IntStr>
and therefore can be used either within a string
or a numeric context.
The group id is therefore obtained via C<+$*GROUP>, while the
group name via C<~$*GROUP>.

=head3 $EFFECTIVE_GROUP_ID, $EGID, $)

The effective group id does not appear to be currently provided by Raku.

=head3 $REAL_USER_ID, $UID, $<

In Raku the user information is handled by C<$*USER>,
which holds an object of type L<IntStr|/type/IntStr>
and therefore can be used either within a string
or a numeric context (this is similar to how the group
information is handled by the C<$*GROUP> object).
The user id is therefore obtained via C<+$*USER>, while the
username via C<~$*USER>.

=head3 $EFFECTIVE_USER_ID, $EUID, $>

The effective user id does not appear to be currently provided by Raku.

=head3 $SUBSCRIPT_SEPARATOR, $SUBSEP, $;

The subscript separator variable is not included in Raku. Frankly, if your
Perl code is using this, it's almost certainly really, really old.

=head3 $a, $b

C<$a> and C<$b> have no special meaning in Raku. C<sort()> does not
use them for anything special. They're just regular old variables.

This feature has been extended by having blocks with placeholder
parameters which are more versatile. Placeholder variables are created
with the C<^> twigil (e. g. C<$^z>. They can be used in a bare block or
in a subroutine without an explicit parameter list. The arguments to
the block are assigned to the placeholder variables in their Unicode
order. I. e. even if the variables appear in the block in the order
C<($^q, $^z, $^a)>, they will be I<assigned> in the order C<($^a, $^q,
$^z)>. Ergo:

=begin code
sort { $^a cmp $^z }, 1, 5, 6, 4, 2, 3;
# OUTPUT: «(1 2 3 4 5 6)␤»
sort { $^g cmp $^a }, 1, 5, 6, 4, 2, 3;
# OUTPUT: «(6 5 4 3 2 1)␤»
for 1..9 { say $^c, $^a, $^b; last }
# OUTPUT: «312␤»
=end code

For more on placeholder variables, see
L<this page|/language/variables#The_^_Twigil>

=head3 %ENV

%ENV has been replaced by %*ENV in Raku. Note that the keys of this hash may
not be exactly the same between Perl and Raku. For example,
C<OLDPWD> is missing from Raku's %ENV.

=head3 $OLD_PERL_VERSION, $]

The running version of Raku is kept by C<$*RAKU> special variable, that is an object.
The running version is retrieved via C<$*RAKU.version>, which returns something
like C<v6.d>; the full stringified version of the Raku interpreter is obtained
via C<$*RAKU.gist>, which returns something like C<Raku (6.d)>.

=head3 $SYSTEM_FD_MAX, $^F

Although the design documents (S28) indicate that this will likely
become C<$*SYS_FD_MAX>, this has not yet been implemented.

=head3 @F

[NEEDS FURTHER RESEARCH] A bit confusing at this point. Design doc S28
indicates that C<@F> in Perl is replaced by C<@_> in Raku, but it's
unclear just how that works. On the other hand, it's currently something of a
moot point, as the Perl to Raku Translation doc indicates that the C<-a>
and C<-F> command-line switches are not yet implemented in rakudo.

=head3 @INC

X<|@INC (Perl)>

No longer exists in Raku.  Please use "use lib" to manipulate the
module repositories to be searched.  The closest thing to @INC is
really $*REPO.  But that works completely differently from @INC mostly
because of the precompilation capabilities of Raku.

     # Print out a list of compunit repositories
     .say for $*REPO.repo-chain;

=head3 %INC

X<|%INC (Perl)>

No longer exists in Raku.  Because each Repository is responsible for
remembering which modules have been loaded already. You can get a list
of all loaded modules (compilation units) like so:

=for code :skip-test<needs dummy module>
use Test;
use MyModule;
say flat $*REPO.repo-chain.map(*.loaded); #-> (MyModule Test)

=head3 $INPLACE_EDIT, $^I

S28 suggests $*INPLACE_EDIT, but it does not yet exist.

=head3 $^M

S28 suggests $*EMERGENCY_MEMORY, but it does not yet exist.

=head3 $OSNAME, $^O

This is somewhat unclear. It probably depends on what you mean by "the name of
the operating system" as design document L<S28|https://design.raku.org/S28.html>
has three different suggestions, all of which
give different answers.

There are currently three main objects containing information about the "running
environment":

=item C<$*KERNEL> provides information about the running Operating System kernel;
=item C<$*DISTRO> provides information about the Operating System distribution;
=item C<$*VM> provides information about the running backend machine for Raku.

All the above objects have methods in common:
=item C<version> provides the version number for that component;
=item C<name> provides the mnemonic name for that component;
=item C<auth> provides the known author(s) for that component.

As a short example, the following piece of code prints information about
all the above components:

=begin code
for $*KERNEL, $*DISTRO, $*VM -> $what {
    say $what.^name;
    say 'version '  ~ $what.version
        ~ ' named ' ~ $what.name
        ~ ' by '    ~ $what.auth;
}

# Kernel
# version 4.10.0.42.generic named linux by unknown
# Distro
# version 17.04.Zesty.Zapus named ubuntu by https://www.ubuntu.com/
# VM
# version 2017.11 named moar by The MoarVM Team
=end code

The C<Str> method on all of the above produces the I<short> version of the information,
at the current time the C<name>.

All the objects have other methods that can be useful when trying to identify the
exact running instance, for more information use <.^methods> to introspect all the above.

=head3 %SIG

No equivalent variable. To have your code executed on the reception of a
signal, you can call the L<signal|/routine/signal#(Supply)_sub_signal>
subroutine, which returns a C<Supply> that can be tapped.

=for code :lang<perl>
$SIG{"INT"} = sub { say "bye"; exit }
=for code
signal(SIGINT).tap: { say "bye"; exit }; loop {}

Or, if you have a generic code that want to know which signal it got:

=for code
signal(SIGINT).tap: -> $signal { say "bye with $signal"; exit }; loop {}

A more idiomatic way of using signals in an event driven situation:

=for code
react {
    whenever signal(SIGINT) {
        say "goodbye";
        done
    }
}

=head3 $BASETIME, $^T

Replaced in Raku by C<$*INIT-INSTANT>. Unlike in Perl, this is not in
seconds since epoch, but an L<Instant|/type/Instant> object, which is measured in atomic
seconds, with fractions.

=head3 $PERL_VERSION, $^V

As with C<$]> this has been replaced with C<$*RAKU.version>.

=head3 ${^WIN32_SLOPPY_STAT}

There is no analog to this in Raku.

=head3 $EXECUTABLE_NAME, $^X

This has been replaced by C<$*EXECUTABLE-NAME>.
Note that there is also C<$*EXECUTABLE>, which is an C<IO> object in Raku.

=head2 Variables related to regular expressions

=head3 Performance issues

As shown below, C<$`>, C<$&>, and C<$'> are gone from Raku, primarily
replaced by variations on C<$/> and, with their elimination, the
associated performance issues in Perl do not apply.

=head3 $<I<digits>> ($1, $2, ...)

These existing variables do the same thing in Raku as they do in Perl,
except that they now start at C<$0> rather than C<$1>. Furthermore, they are
synonyms for indexed items in the match variable C<$/>. I. e. C<$0> is equivalent
to C<$/[0]>, C<$1> is equivalent to C<$/[1]>, etc.

=head3 $MATCH, $&

C<$/> now contains the L<match|/type/Match> object, so the Perl behavior of C<$&> can
be obtained by stringifying it, i. e. C<~$/>.

Please note that while C<$/.Str> should also work,
C<~$/> is currently the more common idiom.

=head3 ${^MATCH}

Since the former performance issues are done away with, this variable is
not of use in Raku.

=head3 $PREMATCH, $`

Replaced by C<$/.prematch>.

=head3 ${^PREMATCH}

Since the former performance issues are done away with, this variable is
not of use in Raku.

=head3 $POSTMATCH, $'

Replaced by C<$/.postmatch>.

=head3 ${^POSTMATCH}

Since the former performance issues are done away with, this variable is
not of use in Raku.

=head3 $LAST_PAREN_MATCH, $+

Does not exist in Raku, but you can get the same information using C<$/[*-
1].Str> (C<$/[*-1]> would be the match object, not the actual string).

If you want to I<understand> why that works, you can look at these documents:

=item L<[ ] routine|/routine/[ ]>

=item L<Whatever|/type/Whatever>

...and possibly

=item L<https://design.raku.org/S02.html#line_1126>

...though the design documents are not always up to date.

=head3 $LAST_SUBMATCH_RESULT, $^N

S28 suggests C<$*MOST_RECENT_CAPTURED_MATCH>, but there does not seem to be
any implemented variable that matches C<$^N>.

=head3 @LAST_MATCH_END, @+

As with most regular expression related variables, this functionality
is, at least in part, moved to the C<$/> variable in Raku. Or, in this
case, the numbered variables that alias to the indexes of it. The offset
is found by using the C<.to> method. I. e. the first offset is
C<$/[0].to>, which is synonymous with C<$0.to>. The value Perl
provides as C<$+[0]> is provided by C<$/.to>.

=head3 %LAST_PAREN_MATCH, %+

Once again, we move over to C<$/>. The former C<$+{$match}> is
C<$/{$match}>.

=head3 @LAST_MATCH_START, @-

Similarly to C<@+> being replaced by using the C<.to> method, C<@-> is
replaced by using the C<.from> method on C<$/> and its variations. The
first offset is C<$/[0].from> or the equivalent C<$0.from>. Perl's C<$-
[0]> is C<$/.from>.


=head3 %LAST_MATCH_START, %-

Much like C<%+>, a use of C<%-{$match}> would be replaced with C<$/{$match}>.

=head3 $LAST_REGEXP_CODE_RESULT, $^R

No equivalent.

=head3 ${^RE_DEBUG_FLAGS}

No equivalent.

=head3 ${^RE_TRIE_MAXBUF}

No equivalent.

=head2 Variables related to filehandles

=head3 $ARGV

The name of the current file when reading lines can be obtained through
C<$*ARGFILES.path>.

=head3 @ARGV

C<@*ARGS> contains the command line arguments.

=head3 ARGV

This has been replaced by C<$*ARGFILES>.

=head3 ARGVOUT

As the C<-i> command line switch has not yet been implemented, there is not
yet an equivalent of C<ARGVOUT>.

=head3 $OUTPUT_FIELD_SEPARATOR, $OFS, $,

Currently no obvious equivalent.

=head3 $INPUT_LINE_NUMBER

=head3 $NR, $.

No direct replacement exists.

When iterating using L<lines|/routine/lines> method from L<IO::Path|/type/IO::Path> or L<IO::Handle|/type/IO::Path> types,
you can call the C<.kv> method on it to get an interleaved list of indexes and values (then iterate by 2 each loop):

=begin code
for "foo".IO.lines.kv -> $n, $line {
    say "{$n + 1}: $line"
}
# OUTPUT:
# 1: a
# 2: b
# 3: c
# 4: d
=end code

For L<IO::CatHandle|/type/IO::CatHandle> types
(of which L«C<$*ARGFILES>|/language/variables#index-entry-%24%2AARGFILES» is
one), you can use L«C<on-switch>|/type/IO::CatHandle#method_on-switch» hook
to reset line number on handle switch, and increment it manually.
See also L«C<IO::CatHandle::AutoLines>|https://modules.raku.org/repo/IO::CatHandle::AutoLines»
and L«C<LN>|https://modules.raku.org/repo/LN» modules that simplify this
operation.

=head3 $INPUT_RECORD_SEPARATOR, $RS, $/

This is accessed through the C<.nl-in> method on the filehandle. E. g.
C<$*IN.nl-in>.

=head3 $OUTPUT_RECORD_SEPARATOR, $ORS, $\

This is accessed through the C<.nl-out> method on the filehandle. E. g.
C<$*OUT.nl-out>.

=head3 $OUTPUT_AUTOFLUSH, $|

No global alternative available. TTY handles are unbuffered by default, for
others, set L<out-buffer|/routine/out-buffer> to zero or use C<:!out-buffer> with L<open|/routine/open> on a
specific L<IO::Handle|/type/IO::Handle>.

=head3 ${^LAST_FH}

Not implemented in Raku.

=head2 Variables related to formats

There are no built-in formats in Raku.

=head2 Error variables

Because of how error variables have changed in Raku, they will not be detailed
here individually.

To quote the Raku L<docs|/language/variables#index-entry-%24!>, "$! is the error variable." That's it.
All the error variables appear to have been eaten by $!. As with the rest of
Raku, it's an object that will return various things depending on the type of error
or L<exception|/type/Exception>.

In particular, when dealing with L<exceptions|/type/Exception> the C<$!> provides information
about the thrown exception, assuming the program has not halted:

=begin code
try {
    fail "Boooh";
    CATCH {
        # within the catch block
        # the exception is placed into $_
        say 'within the catch:';
        say $_.^name ~ ' : ' ~ $_.message;
        $_.resume; # do not abort
    }
}

# outside the catch block the exception is placed
# into $!
say 'outside the catch:';
say $!.^name ~ ' : ' ~ $!.message;
=end code

and the above code produces the following output

=for code :lang<shell>
within the catch:
X::AdHoc : Boooh
outside the catch:
X::AdHoc : Boooh

therefore, as stated before, the C<$!> variable holds the exception object.

=head2 Variables related to the interpreter state

=head3 $COMPILING, $^C, $^D, ${^ENCODING}, ${^GLOBAL_PHASE}

Currently no equivalents for either of these variables.

=head3 $^H, %^H, ${^OPEN}

There may or may not be equivalents of these in Raku, but they're internal
and you shouldn't be messing with them in the first place - certainly not if
your understanding of Raku requires you to read this document...

=head3 $PERLDB, $^P

The chance of the Raku debugger resembling the Perl debugger is slim
at best, and at this point there does not seem to be an equivalent of
this variable.

=head3 ${^TAINT}

S28 claims this variable is "pending". Not currently in Raku.

=head3 ${^UNICODE}, ${^UTF8CACHE}, ${^UTF8LOCALE}

These Unicode-related variables do not appear to exist in Raku, but -
maybe? - could have analogs in C<$?ENC> somewhere. This, however, is
totally unconfirmed.


=end pod

# vim: expandtab softtabstop=4 shiftwidth=4 ft=perl6
