Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Added doc for C<state> to lib/Language/variables.pod
  • Loading branch information
dha committed Sep 14, 2015
1 parent b628b18 commit 87b2b50
Showing 1 changed file with 72 additions and 1 deletion.
73 changes: 72 additions & 1 deletion lib/Language/variables.pod
Expand Up @@ -501,7 +501,78 @@ but still aren't installed in a scope:
=head2 The C<state> Declarator
=comment TODO
C<state> declares lexically scoped variables, just like C<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
=begin code
sub a {
state @x = 1, 1;
@x.push(1, 1)
}
=end code
will continue to append each time it is called. So,
=begin code
say a;
say "next";
say a;
say "next";
say a;
=end code
will output
=begin code
[1 1 1 1]
next
[1 1 1 1 1 1]
next
[1 1 1 1 1 1 1 1]
=end code
Also, just like C<my>, declaring multiple variables must be placed in
parentheses and for declaring a single variable, parentheses may be
omitted. Within a parenthesized list, C<$> can be used as a dummy
placeholder.
In fact, C<$> can be used as an anonymous state variable in subroutines
without a C<state> declaration.
=begin code
perl6 -e 'sub foo() { say ++$ }; foo() for ^3'
=end code
produces
=begin code
1
2
3
=end code
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
=head2 The C<augment> Declarator
Expand Down

0 comments on commit 87b2b50

Please sign in to comment.