leonidlm has asked for the wisdom of the Perl Monks concerning the following question:

Hi all,
I am writing a big perl program
I noticed that in my program sometimes I call a big subroutines with the same parameters all over again.
Is there a module in perl that can act like a buffer and "remember" the last result instead of calling the same subroutine all over again?
I remember I read about something similar to that, meomize or something ...

Replies are listed 'Best First'.
Re: A perl buffer
by ikegami (Patriarch) on Aug 10, 2008 at 13:03 UTC

      It's certainly cool that there's a module for this purpose, however in some cases you can simply write:

      my %cache; my $result = $cache{$input} ||= function($input); print $result;

        ... which fails when function($input) returns the empty string, 0 or undef. These values are often used when the most expensive search came up fruitless :).

      But how I can use it if I need it in a .pm module that acts like a container module, only subs... ?
        you would just say
        
        use Memoize;
        
        memoize('foo');
        sub foo {
        
        }
        
        And if you want to be diligent do a benchmark to see if it is quicker.
        Also, make sure that the functions have no side effects (io, setting global/package variables, etc)


        -pete
        "Worry is like a rocking chair. It gives you something to do, but it doesn't get you anywhere."
        Just like anywhere else? I don't see what's special.
Re: A perl buffer
by dokkeldepper (Friar) on Aug 11, 2008 at 05:20 UTC
    Make an object out of it. Yes, you can bless a sub.