我想使用单行程序通过使用状态变量来打印文件的中间部分,以指示当前行是否在文件的所需部分内.但是我无法初始化状态变量.初始化是如此简单,我只是找不到问题所在.请帮忙.谢谢.
该文件名为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; }'
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,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" /'