File tree Expand file tree Collapse file tree 1 file changed +72
-1
lines changed Expand file tree Collapse file tree 1 file changed +72
-1
lines changed Original file line number Diff line number Diff line change @@ -501,7 +501,78 @@ but still aren't installed in a scope:
501
501
502
502
= head2 The C < state > Declarator
503
503
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
505
576
506
577
= head2 The C < augment > Declarator
507
578
You can’t perform that action at this time.
0 commit comments