通过 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