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

perl

Solution

I've always used scoping braces to create static variables.

add() for 1..2;       # Append to existing.
add('foo', 'bar');    # Re-initialize if args are passed.
add() for 1..2;       # Append to existing.
{
    my @arr;
    sub add {
        @arr = @_ if @_;
        push @arr, '+';
        print @arr, "\n";
    }
}

Problem

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?

Original source