4
我有2个测试文件。在一个文件中,我想使用状态变量作为开关提取中间部分,而在另一个文件中,我想使用状态变量来保存所看到的数字总和。为什么Perl 6状态变量对于不同的文件表现不同?
文件之一:
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
代码来处理文件之一:
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
以及处理文件中的两个代码
cat file2 | perl6 -ne 'state $x=0; if $_ ~~ m/ \d+/{ $x += $/.Str; } ; say $x; '
,结果不出所料:
1
3
6
10
15
什么使状态变量无法在第一代码初始化,但在第二行不行码?
我发现,在第一个代码,如果我状态变量做一些,如加,那么它的工作原理。为什么这样?
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
感谢您的任何帮助。
看起来像一个Rakudo错误。更简单的测试用例:'echo Hello | perl6 -ne'state $ x = 42; dd $ x''。看起来,当使用'-n'或'-p'开关时,顶级状态变量不会被初始化。如果你还没有,请[报告错误](http://rakudo.org/tickets/)。作为解决方法,您可以使用'// ='(赋予未定义的)运算符在单独的语句中手动初始化变量:'state $ x; $ x // = 42;' – smls
谢谢smls!我会报告这个错误! – lisprogtor
@smls我从你的评论中创建一个答案。随意做同样的事情(毕竟是你的评论),然后我会删除我的答案。 (我试图从“未回答”列表中解决)。 –