perl6无法初始化状态变量.需要帮助

lis*_*tor 4 variables state perl6 assign

我想使用单行程序通过使用状态变量来打印文件的中间部分,以指示当前行是否在文件的所需部分内.但是我无法初始化状态变量.初始化是如此简单,我只是找不到问题所在.请帮忙.谢谢.

该文件名为testFile.txt,并包含以下行:

section 0; state 0; not needed
= start section 1 =
state 1; needed
= end section 1 =
section 2; state 2; not needed
Run Code Online (Sandbox Code Playgroud)

我的单行是

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

并且输出显示$ x = 0没有进行初始化:

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--> 
Run Code Online (Sandbox Code Playgroud)

Chr*_*oph 5

这看起来像是一个错误:显然,-n没有正确设置词汇环境.

作为一种解决方法,您可以将整个事物包装在一个块中,例如通过使用do { ... }甚至只是围绕您的代码{ ... }.

另请注意,根据您的使用情况,可以通过使用触发器操作符来简化整个操作,例如

cat testFile.txt | perl6 -ne '.say if / "start" / ff / "end" /'
Run Code Online (Sandbox Code Playgroud)