In Perl before 5.10 there is no "state" declaration.
I've come across an example of creating static variables in these Perls: my $x if 0
. The if 0
conditional makes the variable act like a static variable:
use strict; use warnings;
add() for 1..7;
sub add {
my @arr = () if 0;
push @arr, '+';
print @arr, "\n";
}
prints:
+
++
+++
++++
+++++
++++++
+++++++
Is this behaviour consistent in all versions of Perl before 5.10?
Global and static variables are initialized to their default values because it is in the C or C++ standards and it is free to assign a value by zero at compile time. Both static and global variable behave same to the generated object code. These variables are allocated in .
Static functions can be called directly by using class name. Static variables are initialized only once. Compiler persist the variable till the end of the program. Static variable can be defined inside or outside the function.
For the static variables, we have to initialize them after defining the class. To initialize we have to use the class name then scope resolution operator (::), then the variable name. Now we can assign some value. The following code will illustrate the of static member initializing technique.
A static variable in a block is initialized only one time, prior to program execution, whereas an auto variable that has an initializer is initialized every time it comes into existence.
The behavior of my $x if 0
is a bug. It has survived for a long time because it's useful and thus used; fixing it would break existing code. It's consistent and could therefore be considered usable but that doesn't mean you should do so. This "feature" has been deprecated and issues a warning as of 5.10:
Deprecated use of my() in false conditional
Even if you can't use state
(i.e your code needs to be able to run under versions of Perl prior to 5.10) the my $x if 0
trick is just laziness. Use a closure otherwise:
{
my $x;
sub counter {
$x = '1' unless defined $x;
print $x++, "\n";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With