我想使用单行打印文件的中间部分,通过使用状态变量来指示当前行是否在文件的所需部分内。但我无法初始化状态变量。初始化如此简单,我就是找不到问题所在。请帮忙。谢谢。
该文件名为 testFile.txt,包含以下几行:
section 0; state 0; not needed
= start section 1 =
state 1; needed
= end section 1 =
section 2; state 2; not needed
我的单线是
cat testFile.txt | perl6 -ne ' state $x = 0; say "$x--> "; if $_ ~~ m/ "start" / { $x=1; }; if $x == 1 { .say; }; if $_ ~~ m/ "end" / { $x = 2; }'
并且输出显示 $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-->
最佳答案
这对我来说似乎是一个错误:显然,-n
没有正确设置词法环境。
作为一种解决方法,您可以将整个内容包装在一个块中,例如通过用 do { ... }
包围您的代码。甚至只是 { ... }
.
另请注意,根据您的用例,可以使用 flip-flop operator 简化整个过程。 ,例如
cat testFile.txt | perl6 -ne '.say if / "start" / ff / "end" /'
关于variables - perl6 无法初始化状态变量。需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41237858/