Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the 'my $x if 0' trick usable for static variable creation for Perls before 5.10?

Tags:

perl

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?

like image 291
Eugene Yarmash Avatar asked Jan 29 '10 09:01

Eugene Yarmash


People also ask

Are static variables initialized to zero C++?

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 .

How do you declare and initialize a static variable?

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.

How do you initialize a static variable in CPP?

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.

How many times static member variable is initialized?

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.


1 Answers

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";
    }
}
like image 106
Michael Carman Avatar answered Nov 15 '22 15:11

Michael Carman