通过Perl中的state()状态变量
Perl中还有另一种词法变量,它类似于私有变量,但是它们保持其状态,并且在多次调用子例程时不会重新初始化它们。这些变量是使用状态运算符定义的,并且从Perl5.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
在Perl5.10之前,您必须像这样编写它-
示例
#!/usr/bin/perl
{
my $count = 0; # initial value
sub PrintCount {
print "Value of counter is $count\n";
$count++;
}
}
for (1..5) {
PrintCount();
}热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短