manually expire an element in Memoize

D

danielmcbrearty

hi all

I like and use MJ Dominus' excellent Memoize module to cache some
stuff in my app that hits a db rather hard. It's very simple :


use Memoize;

memoize('my_accessor');

sub my_accessor {
my ($key1, $key2) = @_;
# look up $key1, $key2 in the db and return a scalar
}

and the function is magically cached without the need to do any more.

Now what I'd like is, in another function, to manually invalidate (or
delete) certain cached values at runtime (most likely because I
changed the value in the db).

How can I do this? I looked at the docs and source for
Memoize::Expire, but it's not too clear to me right now. Obviously,
I'd like the simplest possible solution ...

thanks

Daniel
 
G

gf

hi all

I like and use MJ Dominus' excellent Memoize module to cache some
stuff in my app that hits a db rather hard. It's very simple :

use Memoize;

memoize('my_accessor');

sub my_accessor {
my ($key1, $key2) = @_;
# look up $key1, $key2 in the db and return a scalar

}

and the function is magically cached without the need to do any more.

Now what I'd like is, in another function, to manually invalidate (or
delete) certain cached values at runtime (most likely because I
changed the value in the db).

How can I do this? I looked at the docs and source for
Memoize::Expire, but it's not too clear to me right now. Obviously,
I'd like the simplest possible solution ...

Memoize is cool, but if you need more flexibility or other features
then rolling a simple version isn't hard.

Wrap your function in an extra set of braces kinda like this ...

{
my %memo_cache;
sub blah {
return $memo_cache{@_} if $memo_cache{@_};
...
my $return_value =
do_some_calculating_to_create_a_return_value...
...
$memo_cache{@_} = $return_value;
return $return_value;
}
}


If you need to be able expire an element in your cache then you add an
additional sub inside the outer braces...

{
my %memo_cache;

sub drop_cache_value {
delete $memo_cache{@_};
}

sub blah {
return $memo_cache{@_} if $memo_cache{@_};
...
my $return_value =
do_some_calculating_to_create_a_return_value...
...
$memo_cache{@_} = $return_value;
return $return_value;
}

}

And call the drop_cache_value() with the same values used to initially
create the memoized entry when you determine that that element in the
hash needs to be deleted.

The downside of doing it yourself is you might not handle conditions
that Memoize or a similar module already handles.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,042
Latest member
icassiem

Latest Threads

Top