透過 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();
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓系統
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP