Sure, let me try to explain what I want to do.

We have a bunch of objects of different classes. They all have a lot of methods, more than I would want to list by hand.

Not knowing until run time which class or which methods I will want, I would like to be able to interpolate method calls into a template.


# this is the module I wrote to do this, would prefer something else
use InterpolateMethods qw(interpolate_methods);

# this is an example, in practice templates will not
# be statically defined, but loaded in from a file or
# something of that sort
$pubtemplate = q[title: $title, by $authors]; # note single quotes

# @manypubs is an array of NBER::Publication objects
# NBER::Publication supports ->title and ->authors
foreach my $publication(@manypubs) {
  print(interpolate_methods($publication,$pubtemplate));
}

#output:
# title: A Plan For Spam, by Paul Graham
# we got this by calling $publication->title
# and $publication->authors


I hope that is clear.

I misunderstood what someone was suggesting, but basically

 s/\$(\w+)/$object->$1()/sgex;

will work, except that I did not trust my own regexp. Better:

 s/\$(\w+)/ $object->can($1) ? $object->$1() : '$' . $1 /sgex

that will leave the orignal text untouched unless there is a method available. Is there a better regexp than \$(\w+) to identify anything that the perl parser would identify as a variable?

Thanks for all the responses, this is very helpful.

 - Alex







On Wed, 26 May 2010, Uri Guttman wrote:

"JP" == Jerrad Pierce <belg4...@pthbb.org> writes:

 JP> Other than some abstract fear of tie, what's wrong with Interpolation?
 JP> As implemented, you could easily Memoize the subroutine you bind as your
 JP> handler. You can even easily bind two versions, one that memoizes and
 JP> another that does not.

i am confused by your statement. i have no abstract fear of tied. it is
just known to be slow and not needed here. why use a complex solution
when simpler ones exist? and where did i say not to use interpolation? i
said just use it in the best way. i am against eval for this, not
interpolation. IMO the best solution is a hash of the method call
results and interpolating the hash entries. but as i said, the OP has
not stated the real top level requirements clearly. only some short
comments about multiple methods and reusing objects were made. if that
is cleared up then a best practice solution could be posited.

uri



--
 - Alex Aminoff
   BaseSpace.net

_______________________________________________
Boston-pm mailing list
Boston-pm@mail.pm.org
http://mail.pm.org/mailman/listinfo/boston-pm

Reply via email to