Damien Krotkine home

Simple usage of Perl state variables

I see this type of code too often:

package Foo;
{
  my $structure = {};
  sub plop {
      #...
      $structure->{$foo} = 'bar';
      #...
  }
}

Or things like that:

package Foo;
{
  my $cache;
  sub plop {
      #...
      defined $cache or $cache = _load_cache();
      #...
  }
}

If you are using a non-ancient version of Perl (that is, 5.10 or more), you should consider using the state keyword. It’s similar to the static variables inherited from C.

From the documentation : > state declares a lexically scoped variable, just like my does. However, those > variables will never be reinitialized, contrary to lexical variables that are > reinitialized each time their enclosing block is entered.

So the two code snippets become :

package Foo;
sub plop {
    state $structure = {};
    $structure->{$foo} = 'bar';
    #...
}

and:

package Foo;
sub plop {
    #...
    state $cache = _load_cache();
    #...
}

Nothing terribly amazing here, but it’s really easy, saves keystrokes and makes the code more readable. So why not use it more widely ?

blog comments powered by Disqus
Fork me on GitHub