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?


In reply to Regarding variables that by mr.nick

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.