I'm working on a simple little caching mechanism for my webapp when I move it over to mod_perl. I've looked at some of the CPAN solutions, but I really need to do this from scratch since this app. will have to run on systems where new modules can't/won't be installed.

Basically what I have is a subroutine Cache::cache() which you call with three arguments: a key, a subroutine reference, and a timeout value. The cache subroutine decides whether or not to run the subref and returns the output of the subref (either the cached or new output).

What do the wise monks think of this approach?

#!/usr/bin/perl -w # This script runs under mod_perl use strict; use CGI qw(:standard); my %data = Cache::cache('info',\&do_it,200); print header('text/html'); print start_html(); print p([$data{data},$data{source},$data{'time'},"Process: $$"]); print end_html(); sub do_it { # do something that takes a long time my $text = `ls -lR /`; return length($text); } package Cache; sub cache { our (%time, %asdf); my ($key, $sub, $time) = @_; if((not defined $asdf{$key}) or (not defined $time{$key}) or ($tim +e{$key} < time - $time)){ $time{$key} = time; $asdf{$key} = &$sub; my %out = (data => $asdf{$key}, 'time' => $time{$key}, source +=> 'db_query'); return %out; } else{ my %out = (data => $asdf{$key}, 'time' => $time{$key}, source +=> 'cache_query'); return %out; } }

-caedes


In reply to Caching data with mod_perl by caedes

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.