gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 06:57:00 24 4
gpt4 key购买 nike

我有 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;

关于variables - 为什么 Perl 6 状态变量对于不同的文件表现不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41320167/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com