[ABE.pm] HOP Q

Ricardo SIGNES rjbs-perl-abe at lists.manxome.org
Wed Sep 27 20:00:57 PDT 2006

* "Faber J. Fedor" <faber at linuxnj.com> [2006-09-27T19:30:56]
> However, there's one notation in his code examples that I don't grok.
> Using the memoize-norm2 example in his book
> (http://hop.perl.plover.com/Examples/memoize-norm2), he does this:
> sub memoize {
>     my ($func, $keygen) = @_;
>     ...
>     $cache{$key} = $func->(@_) unless exists $cache{$key};
>     ...
> }
> where $func is a coderef.
> [ snip ]
> Or am I completely off-base?

You basically just said:

  I met her at the library.  We went for drinks.  Yadda yadda yadda, she woke
  me up when she made me breakfast.

You can't just yadda yadda yadda out the good stuff!

Your ... above includes a sub declaration.  The "$func->(@_)" is inside sub {},
which means that its @_ is not the same as the enclosing sub's @_.  Its @_ is
defined when that sub is called.

Here is the full example:

  sub memoize {
    my ($func, $keygen) = @_;
    my %cache;
    my $stub = $keygen ? 
      sub { my $key = $keygen->(@_);
            $cache{$key} = $func->(@_) unless exists $cache{$key};
            return $cache{$key};
      sub { my $key = join ',', @_;
            $cache{$key} = $func->(@_) unless exists $cache{$key};
            return $cache{$key};
    return $stub;

memoize is returning $stub, which is a new code reference.  $stub's code
reference has a reference to $func, the original code, and can call it.

Reread this example again, paying particular attention to the fact that the
sub{}s included in it are data that will be returned, not code that is
immediately executed.  Is it clearer?


More information about the ABE-pm mailing list