bduggan has asked for the wisdom of the Perl Monks concerning the following question:
So, my questions are :# In the various classes : __PACKAGE__->setupMemoizedSubs( methodname => sub { my $self = shift; #... do resource-intensive stuff .. }, anothermethod => sub { ... }, ) # In a common base class : sub setupMemoizedSubs { my ($class,%args) = @_; no strict 'refs'; while (my ($name,$sub) = each %args) { my $private_element = "__memoized_$name"; *{"${class}::$name"} = sub { my $self = shift; $self->_set($private_element => $_[0]) if @_==1; return $self->_get($private_element) if $self->_is_set($private_element); $self->_set($private_element => $sub->($self)); $self->_get($private_element); }; } use strict 'refs'; } # Somewhere else $object->methodname("pre-computed value"); # set the value $object->methodname(); # Gets the value we set # Or if we omit the first one... $object->methodname() # Actually calls the method
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Memoizing Methods
by hv (Prior) on Mar 29, 2006 at 19:48 UTC | |
|
Re: Memoizing Methods
by davidrw (Prior) on Mar 29, 2006 at 17:07 UTC | |
by bduggan (Pilgrim) on Mar 29, 2006 at 17:24 UTC | |
|
Re: Memoizing Methods
by eric256 (Parson) on Mar 29, 2006 at 17:34 UTC | |
by bduggan (Pilgrim) on Mar 29, 2006 at 18:01 UTC |