in reply to A perl buffer

Memoize

Replies are listed 'Best First'.
Re^2: A perl buffer
by betterworld (Curate) on Aug 10, 2008 at 16:06 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 :).

        I knew that someone would find this loophole ;)

        Well, it would not exactly "fail", it would just ignore the cache. Perl 5.10 has help for us:

        my $result = $cache{$input} //= function($input);

        Of course, there might still be the case where the function returns undef or a list or depends on the context. Before conjuring up a perfect solution that honours all special cases, I'd better let you use Memoize as recommended above :)

Re^2: A perl buffer
by leonidlm (Pilgrim) on Aug 10, 2008 at 13:12 UTC
    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."
        Ahh now I see my problem:
        My function receiving different parameters. For example I configured a database retrive function. As a parameter I receive the sql statement. Sometimes my application will call this retrive function with the same sqlstatement, only in this case I want to memorize it and return the "memorized" image without retriving the data again.
        Now I hope I am clear :)
        BTW thanks everyone for helping.
      Just like anywhere else? I don't see what's special.