变量 – 为什么Perl 6状态变量对不同的文件表现不同?

我有2个测试文件.在一个文件中,我想使用状态变量作为开关来提取中间部分,而在另一个文件中,我想使用状态变量来保存所看到的数字之和.

文件一:

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

谢谢你的帮助.

最佳答案 这在smls的评论中得到了回答:

Looks like a Rakudo bug. Simpler test-case:
echo Hello | perl6 -ne 'state $x = 42; dd $x'.
It seems that top-level state variables are
not initialized when the -n or -p switch is used. As a work-around, you can manually initialize the variable in a separate statement, using the //= (assign if undefined) operator:
state $x; $x //= 42;

点赞