Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Make C<$> explanation a little clearer
It seemed that the anonymous state variable was a bit lost in the
rest of the state variable discussion so it merited a section of its
own. Also clarify that each reference is a separate variable.
  • Loading branch information
jonathanstowe committed Dec 8, 2015
1 parent 2dcd172 commit 931726a
Showing 1 changed file with 46 additions and 10 deletions.
56 changes: 46 additions & 10 deletions doc/Language/variables.pod
Expand Up @@ -552,20 +552,22 @@ called. So it will output
=end code
As seen in this example, C<$> can be used as an anonymous state variable
without an explicit C<state> declaration.
As with C<my>, declaring multiple C<state> variables must be placed
in parentheses and for declaring a single variable, parentheses may
be omitted.
=head3 The C<$> Variable
As well as explicitly declared named state variables C<$> can be used
as an anonymous state variable without an explicit C<state> declaration:
=begin code
perl6 -e 'sub foo() { say ++$ }; foo() for ^3'
=end code
produces
produces:
=begin code
Expand All @@ -575,26 +577,28 @@ produces
=end code
Furthermore, state variables are not required to exist in
subroutines. You could, for example, use C<$> in a one-liner to
number the lines in a file.
There is no L<Positional> (C<@>) or L<Associative> (C<%>) equivalent, so a
named state variable must be used for those cases.
Furthermore, state variables are not required to exist in subroutines. You
could, for example, use C<$> in a one-liner to number the lines in a file:
=begin code
perl6 -ne 'say ++$ ~ " $_"' example.txt
=end code
Finally, if you were to use multiple anonymous state variables, they would
fuction independently.
Each reference to C<$> within a lexical scope in effect is a separate
variable, as illustrated by:
=begin code
perl6 -e '{ say ++$; say $++ } for ^5'
=end code
would produce
which produces:
=begin code
Expand All @@ -611,6 +615,38 @@ would produce
=end code
If you need to refer to the value of C<$> more than once within the
scope it should be copied to a new variable, for example:
=begin code
sub foo() {
given ++$ {
when 1 {
say "one";
}
when 2 {
say "two";
}
when 3 {
say "three";
}
default {
say "many";
}
}
}
foo() for ^3;
=end code
produces:
=begin code
one
two
three
=end code
=head2 The C<augment> Declarator
With C<augment>, you can add attributes and methods to existing classes and
Expand Down

0 comments on commit 931726a

Please sign in to comment.