Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I was just thinking why we don't have c style static variable in perl, we use $var ||= 1 to set value when there is no initial value defined, why can't this be used for declare a static variable when used with my() my $var ||= 1

Replies are listed 'Best First'.
Re: idea for an static variable
by GrandFather (Saint) on Jul 14, 2006 at 00:03 UTC

    Generally you can achieve the same result by using a global variable. Sometimes you may need to constrain the scope of such a global variable to the context of a sub. You can do that by:

    { my $pseudoStatic = 0; sub usingPseudoStatic { return ++$pseudoStatic; } }

    DWIM is Perl's answer to Gödel
Re: idea for an static variable
by ambrus (Abbot) on Jul 13, 2006 at 23:57 UTC

    That's not what a static variable does in C.

    A static variable in C does two different things depending on what scope it's defined in: if it's in file scope, it is local to a source file (compilation unit); if inside a function, it's a variable that has only one instance and not separate instances in every function. C also has static functions and static class members in C++ but those also mean something like one of these and not default values like you're saying.

Re: idea for an static variable
by duff (Parson) on Jul 14, 2006 at 04:29 UTC

    Perl6 has a similar thing to C-style static vars. Except they're declared with the state declarator. In the following code the variable $x will maintain its value across successive invocations of the subroutine and is only visible within the subroutine:

    sub foo { state $x = 1; say $x++; } foo; # outputs 1 foo; # 2 foo; # 3

    Perl6 is full of all sorts of interesting declarators. See http://dev.perl.org/perl6/doc/design/syn/S03.html#Declarators