variables - perl6 无法初始化状态变量。需要帮助

标签 variables state assign raku

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

该文件名为 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/

相关文章:

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

javascript - 如何改善ReactJS中的设置状态?

c - C中同时赋值给两个指针

python - 以 3 为一组分配列值 - Python

c++ how-to : import numeric variables from . txt 或 .csv 文件

javascript - 在 JavaScript 中用冒号声明一个变量

PHP变量初始化到数据库查询

android - onCreateDrawableState 从不调用

react-native - 在 React Native 中将状态从子组件传递到父组件

php - 取名为数组键名的变量