perl6 Unable to initialize a state variable. Help needed

117 views Asked by At

I want to use a one-liner to print a middle section of a file by using a state variable to indicate whether the current line is within the desired section of the file. But I am unable to initialize the state variable. Initialization is so simple, and I just cannot find what the problem is. Please help. Thanks.

The file is name testFile.txt and has the following lines:

section 0; state 0; not needed
= start section 1 =
state 1; needed
= end section 1 =
section 2; state 2; not needed

And my one-liner is

cat testFile.txt | perl6 -ne ' state $x = 0; say "$x--> "; if $_ ~~ m/ "start" / { $x=1; }; if $x == 1 { .say; }; if $_ ~~ m/ "end" / { $x = 2; }'

And the output showed that $x=0 is not doing initialization:

Use of uninitialized value $x of type Any in string context.
Methods .^name, .perl, .gist, or .say can be used to stringify it to something meaningful.
  in block  at -e line 1
--> 
Use of uninitialized value of type Any in numeric context
  in block  at -e line 1
Use of uninitialized value $x of type Any in string context.
Methods .^name, .perl, .gist, or .say can be used to stringify it to something meaningful.
  in block  at -e line 1
--> 
= start section 1 =
1--> 
state 1; needed
1--> 
= end section 1 =
2--> 
2--> 
1

There are 1 answers

3
Christoph On BEST ANSWER

This looks like a bug to me: Apparently, -n does not properly set up a lexical environment.

As a workaround, you can wrap the whole things in a block, eg by surrounding your code with do { ... } or even just { ... }.

Also note that depending on your use case, the whole thing can probably be simplified by using the flip-flop operator, eg

cat testFile.txt | perl6 -ne '.say if / "start" / ff / "end" /'