2009/11/24 Randal L. Schwartz <mer...@stonehenge.com>:
>>>>>> "Dermot" == Dermot  <paik...@googlemail.com> writes:
>
>
> ...
>
> Dermot> I guess the question is: Will the declaration of our %cache within a
> Dermot> function-orientated sub-routine render it always uninitialized?
>
> I believe what you are seeing is that %cache is per-child, so it has
> to compute it *once* for each child, not once for the server overall.

Actually I've made a bobo. This program doesn't run within modperl but
from the command-line. It updates a DB. But it worked really well. A
few print statements show that the hash is initialised once at the
first invocation of the get_cached_val_or_lookup().

package MyPack::Handlers;

our %cache;

...
..
sub get_cached_val_or_lookup {
    my $val = shift;
    return $cache{$val} ||= do {
        print STDERR "Having to lookup value for $val as the hash key
didn't exist\n";
        my $sql = qq(SELECT DISTINCT price_code, price_id FROM prices);
        my $dbq = dbiQuery($sql);
        if ($dbq->success && $dbq->rows) {       # DBI sub-classed methods
            while ( $dbq->fetch() ) {
                my $code = ($dbq->row())[0];
                $cache{$code} = ($dbq->row())[1];
            }
            return $cache{$val};
        }
    }
}

1;

One more question If I can. Chas pointed me to
http://perldesignpatterns.com/?PerlDesignPatterns some time ago. I
suspect that the above is a form of design pattern. Does it have a
name? Is there a reference to it at
http://perldesignpatterns.com/?PerlDesignPatterns

Thanx,
Dp.

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to