in reply to Caching process sets

Memoize

---
demerphq


Replies are listed 'Best First'.
Re: Re: Caching process sets
by billyak (Friar) on Feb 19, 2003 at 20:59 UTC
    A specific event line does more than what a return is made to do. I would need a seperate subroutine for each of my cached lines. Hence, the eval I mentioned in the original post.

    -billyak

      Instead of just evaling the code, wrap the code in an anonymous sub, thus capturing it so you can resuse it. So we have a routine called parse_to_actions that builds a bunch of lines of perl statements that need to be executed. Then we do this:

      my %code_cache; while (<>) { my $code=$code_cache{$_}; unless ($code) { my @actions=parse_to_actions($_); $code=eval "sub { @actions }" or die "$@ while evaling actions @actions "; $code_cache{$_}=$code; } $code->(); }
      Similar to what xmath posted, but building the subs dymacially.

      However when you consider that we can define parse_to_actions to return a sub, then we could

      use Memoize; sub parse_to_actions { return eval "sub { @lines_of_code }" or die $@; } memoize("parse_to_actions"); while (<>) { #Parse and generate. Memoize caches. parse_to_actions($_)->($_); # pass the line to the generated sub # just in case it gets smart }

      ---
      demerphq


      It's still not entirely clear to me what you're doing, but it sounds like you want are (anonymous) sub references.

      This code would check if an action correponding to $key is known, determine the action if it's not known, and in either case execute the action:

      ($actions{$key} ||= determine_action($key))->($key, $data);
      The sub determine_action would have to find out what the correct action is, and return a sub reference to it. If you don't want to make explicit subs, use anonymous ones:
      sub determine_action { my ($key) = @_ if (it's first action) { return sub { my ($key, $data) = @_; do stuff; }; elsif (it's second action) { return sub { my ($key, $data) = @_; do stuff; }; ... etc... }