Variables 为什么Perl 6状态变量对于不同的文件表现不同?
我有两个测试文件。在一个文件中,我想使用状态变量作为开关来提取中间部分,在另一个文件中,我想使用状态变量来保存看到的数字的总和 文件一:Variables 为什么Perl 6状态变量对于不同的文件表现不同?,variables,initialization,state,raku,Variables,Initialization,State,Raku,我有两个测试文件。在一个文件中,我想使用状态变量作为开关来提取中间部分,在另一个文件中,我想使用状态变量来保存看到的数字的总和 文件一: section 0; state 0; not needed = start section 1 = state 1; needed = end section 1 = section 2; state 2; not needed 文件二: 1 2 3 4 5 处理文件1的代码: cat file1 | perl6 -ne 'state $x = 0; s
section 0; state 0; not needed
= start section 1 =
state 1; needed
= end section 1 =
section 2; state 2; not needed
文件二:
1
2
3
4
5
处理文件1的代码:
cat file1 | perl6 -ne 'state $x = 0; say " x is ", $x; if $_ ~~ m/ start / { $x = 1; }; .say if $x == 1; if $_ ~~ m/ end / { $x = 2; }'
结果是错误的:
x is (Any)
Use of uninitialized value of type Any in numeric context
in block at -e line 1
x is (Any)
= start section 1 =
x is 1
state 1; needed
x is 1
= end section 1 =
x is 2
x is 2
处理文件2的代码是
cat file2 | perl6 -ne 'state $x=0; if $_ ~~ m/ \d+ / { $x += $/.Str; } ; say $x; '
结果如预期:
1
3
6
10
15
是什么导致状态变量在第一个代码中无法初始化,但在第二个代码中可以初始化?
我发现在第一个代码中,如果我让state变量做一些事情,比如加法,那么它就工作了。为什么会这样
cat file1 | perl6 -ne 'state $x += 0; say " x is ", $x; if $_ ~~ m/ start / { $x = 1; }; .say if $x == 1; if $_ ~~ m/ end / { $x = 2; }'
# here, $x += 0 instead of $x = 0; and the results have no errors:
x is 0
x is 0
= start section 1 =
x is 1
state 1; needed
x is 1
= end section 1 =
x is 2
x is 2
感谢您的帮助。这在smls的评论中得到了回答:
看起来像一只Rakudo虫子。更简单的测试用例:
echo Hello | perl6-ne'state$x=42;dd$x'
似乎顶级状态变量是 使用
-n
或-p
开关时未初始化。作为解决方法,您可以使用/=
(未定义时赋值)运算符在单独的语句中手动初始化变量:state$x$x/=42代码>
看起来像一只Rakudo虫子。更简单的测试用例:echo Hello | perl6-ne'state$x=42;dd$x'
。使用-n
或-p
开关时,顶级状态变量似乎未初始化。如果你还没有。作为一种解决方法,您可以使用/=
(未定义时赋值)运算符在单独的语句中手动初始化变量:state$x$x/=42代码>谢谢smls!!我会报告这个错误@smls我正在根据您的评论创建一个答案。请随意做同样的事情(毕竟这是你的评论),然后我会删除我的答案。(我正试图从“未答复”列表中去掉这一点)。