State Variables via state() in Perl

PERLServer Side ProgrammingProgramming Scripts

There is another type of lexical variable in Perl, which is similar to private variables but they maintain their state and they do not get reinitialized upon multiple calls of the subroutines. These variables are defined using the state operator and available starting from Perl 5.9.4.

Example

Let's check the following example to demonstrate the use of state variables −

 Live Demo

#!/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();
}

Output

When the above program is executed, it produces the following result −

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

Prior to Perl 5.10, you would have to write it like this −

Example

 Live Demo

#!/usr/bin/perl
{
   my $count = 0; # initial value
   sub PrintCount {
      print "Value of counter is $count\n";
      $count++;
   }
}
for (1..5) {
   PrintCount();
}
raja
Published on 29-Nov-2019 07:06:24
Advertisements