Skip to content

Commit 87b2b50

Browse files
committed
Added doc for C<state> to lib/Language/variables.pod
1 parent b628b18 commit 87b2b50

File tree

1 file changed

+72
-1
lines changed

1 file changed

+72
-1
lines changed

lib/Language/variables.pod

Lines changed: 72 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -501,7 +501,78 @@ but still aren't installed in a scope:
501501
502502
=head2 The C<state> Declarator
503503
504-
=comment TODO
504+
C<state> declares lexically scoped variables, just like C<my>. However,
505+
initialization happens exactly once the first time the initialization
506+
is encountered in the normal flow of execution. Thus, state variables
507+
will retain their value across multiple executions of the enclosing
508+
block or routine.
509+
510+
Therefore, the subroutine
511+
512+
=begin code
513+
514+
sub a {
515+
state @x = 1, 1;
516+
@x.push(1, 1)
517+
}
518+
519+
=end code
520+
521+
will continue to append each time it is called. So,
522+
523+
=begin code
524+
525+
say a;
526+
say "next";
527+
say a;
528+
say "next";
529+
say a;
530+
531+
=end code
532+
533+
will output
534+
535+
=begin code
536+
537+
[1 1 1 1]
538+
next
539+
[1 1 1 1 1 1]
540+
next
541+
[1 1 1 1 1 1 1 1]
542+
543+
=end code
544+
545+
Also, just like C<my>, declaring multiple variables must be placed in
546+
parentheses and for declaring a single variable, parentheses may be
547+
omitted. Within a parenthesized list, C<$> can be used as a dummy
548+
placeholder.
549+
550+
In fact, C<$> can be used as an anonymous state variable in subroutines
551+
without a C<state> declaration.
552+
553+
=begin code
554+
555+
perl6 -e 'sub foo() { say ++$ }; foo() for ^3'
556+
557+
=end code
558+
559+
produces
560+
561+
=begin code
562+
563+
1
564+
2
565+
3
566+
567+
=end code
568+
569+
You could, for example, use C<$> in a one-liner to number the lines in a file.
570+
571+
=begin code
572+
573+
perl6 -ne 'say "{++$} $_"' example.txt
574+
575+
=end code
505576
506577
=head2 The C<augment> Declarator
507578

0 commit comments

Comments
 (0)