mr.nick has asked for the wisdom of the Perl Monks concerning the following question:

My question of the weekend: as I have learned, you cannot do the following:
sub outer { my $x; $x=shift; sub inner { print "x is $x\n"; } }
and expect $x to be dynamic. This I understand. What I don't understand is how to accomplish something.

A little background: I have a class (let's call it Node.pm) that uses another class (Cache.pm) to cache calls to and from the DBI handler. Something like this pseudo-code:
package Node; use Cache; my $cache=new Cache; sub new { ## blah blah $self; } sub get { my $self=shift; my $id=shift; if (my $data=$cache->check($id)) { return $data; } ## blah blah } 1;
The concept is that regardless of how many instances of Node:: that you create, the same Cache:: object will be used to improve performance.

This is wonderful until I converted the app to work under mod_perl. Now I can't figure out a way of maintaining a single cache for all instances.

Using use vars qw($cache) is fine to preserve the dynamic nature of $cache, but it keeps the $cache object alive across invocations of CGI (which is A Bad Thing because another thread might have modified the object and this instance has no knowledge of it).

What I want is for $cache to behave like it would under a normal CGI; it's created at the beginning of the execution of the script and dies at the end.

If this was in the main cgi-bin and not a class, I could do something like:

{ $cache=new Cache; } ## everything { undef $cache; }
But this won't work inside a module (because mod_perl only executes the class once when loading it for the first time).

Assuming this was moderately understandable (which I doubt), does anyone have any suggestions or ideas?

Replies are listed 'Best First'.
Re (tilly) 1: Regarding variables that
by tilly (Archbishop) on Mar 05, 2001 at 09:47 UTC
    If you use the module, then you can just write an import method that reinitializes the cache.

    This will, of course, only work if the script itself uses the module.

(dkubb) Re: (2) Persistent Variables
by dkubb (Deacon) on Mar 05, 2001 at 12:38 UTC

    You'd like to share information between different processes without using a database? Check out the IPC::* modules on CPAN. They'll let you access and store information in shared memory.

    IPC::ShareLite in particular is great - it's tested and stable in a mod_perl environment. I've used it quite regularly, with mod_perl as part of another module, and I've had no problems with it.

      Not between process instances, but between multiple instances of the same class in one process. And I figured it out. It was as simple as:
      sub init { ## initialize stuff $cache=new GNS::Cache; } sub uninit { undef $cache; }
      then from the main program, I can just do a
      GNS::Node::init(); my $x=new GNS::Node; my $y=new GNS::Node; ## blah blah blah ## do some stuff GNS::Node::uninit();