透過 Perl 中的 state() 設定狀態變數


Perl 中還有另一種型別的詞法變數,它類似於私有變數,但是它們保持其狀態,在多次呼叫子例程時也不會重新初始化。這些變數使用 state 運算子定義,並從 Perl 5.9.4 開始提供。

示例

讓我們檢視以下示例來演示狀態變數的使用 −

 線上演示

#!/usr/bin/perl
use feature 'state';
sub PrintCount {
   state $count = 0; # initial value
   print "Value of counter is $count\n";
   $count++;
}
for (1..5) {
   PrintCount();
}

輸出

當執行上述程式時,它會產生以下結果 −

Value of counter is 0
Value of counter is 1
Value of counter is 2
Value of counter is 3
Value of counter is 4

在 Perl 5.10 之前,您必須像這樣編寫它 −

示例

 線上演示

#!/usr/bin/perl
{
   my $count = 0; # initial value
   sub PrintCount {
      print "Value of counter is $count\n";
      $count++;
   }
}
for (1..5) {
   PrintCount();
}

更新時間: 2019 年 11 月 29 日

684 次瀏覽

開啟 您的職業生涯

完成課程獲得認證

開始使用
廣告
© . All rights reserved.