Perl中还有另一种词法变量,它类似于私有变量,但是它们保持其状态,并且在多次调用子例程时不会重新初始化它们。这些变量是使用状态运算符定义的,并且从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();
}