【问题标题】:Why do Perl 6 state variable behave differently for different files?为什么 Perl 6 状态变量对不同文件的行为不同?
【发布时间】:2016-12-25 09:52:18
【问题描述】:

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

感谢您的帮助。

【问题讨论】:

  • 看起来像一个 Rakudo 错误。更简单的测试用例:echo Hello | perl6 -ne 'state $x = 42; dd $x'。使用-n-p 开关时,似乎没有初始化顶级状态变量。如果您还没有,请report the bug。作为一种解决方法,您可以在单独的语句中手动初始化变量,使用 //=(如果未定义则赋值)运算符:state $x; $x //= 42;
  • 谢谢 smls !!我会报告这个错误!
  • @smls 我正在根据您的评论创建答案。随意做同样的事情(毕竟这是你的评论),然后我会删除我的答案。 (我正在尝试将其从“未答复”列表中删除)。

标签: variables initialization state raku


【解决方案1】:

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

看起来像一个 Rakudo 错误。更简单的测试用例:
echo Hello | perl6 -ne 'state $x = 42; dd $x'.
似乎顶级状态变量是 使用-n-p 开关时未初始化。作为一种解决方法,您可以在单独的语句中手动初始化变量,使用 //=(如果未定义则赋值)运算符:
state $x; $x //= 42;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-19
    • 2020-04-04
    • 2019-11-23
    • 2013-10-30
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 2023-02-10
    相关资源
    最近更新 更多