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我從你的評論中創建一個答案。隨意做同樣的事情(畢竟是你的評論),然後我會刪除我的答案。 (我試圖從「未回答」列表中解決)。 –