>>>>> "AA" == Alex Aminoff <[email protected]> writes:
AA> I want to interpolate methods in a string as scalars. I wrote some
AA> code that works, but my questions are
AA> 1) I couldn't find a pre-existing module that does any of this. Can
AA> that really be true?
AA> 2) I'm not happy with this solution. In particular, what is the scope
AA> of the tied ${$symbol} ? Will it go out of scope at the end of the
AA> call to interpolate_methods? If not, then each call to
AA> interpolate_methods will clutter up namespace and memory with a bunch
AA> of little tied scalar objects.
AA> package NBER::InterpolateMethods;
AA> use base Exporter;
AA> our @EXPORT = qw(interpolate_methods);
AA> sub interpolate_methods {
AA> my($object,$template) = @_;
AA> my $class = ref($object);
AA> my $namespace = $class . '::';
AA> foreach my $symbol ( keys %$namespace ) {
AA> if ( $object->can($symbol) ) {
AA> tie(${$symbol}, 'NBER::TieMethodScalar', $object, $symbol);
AA> }
AA> }
AA> my $out = eval $template;
that isn't needed. eval is slow and can be VERY dangerous. there are
many other ways to interpolate stuff into string.
AA> $@ and die "Error parsing template: $@ $!";
AA> return $out;
AA> }
AA> package NBER::TieMethodScalar;
wow. you went all out crazy to do this! eval string AND tied stuff! slow
and slower!
first off there are the old hackish ways of doing this with
dereferencing anon refs with code inside:
"text${\$foo->method()}more text"
"t...@{[$foo->method()]}more text"
note that in both cases the method (or sub) is called in list
context. this style is frowned upon for production code as it is noisy
and not easy to read.
an old reliable way is using sprintf as long as you don't have too many
fields which again makes it noisy.
sprintf "text%smore text", $foo->method() ;
if you want more templating without all the eval fuss and tied stuff,
try my module Template::Simple. it would be very easy to use this for
method interpolation:
use Template::Simple ;
my $tmpl = Template::Simple->new() ;
my $out = render( "text[%STUFF%]more text",
{ STUFF => $foo->method() } ) ;
so no eval or tied is ever needed for basic stuff like interpolating
methods and subs.
uri
--
Uri Guttman ------ [email protected] -------- http://www.sysarch.com --
----- Perl Code Review , Architecture, Development, Training, Support ------
--------- Gourmet Hot Cocoa Mix ---- http://bestfriendscocoa.com ---------
_______________________________________________
Boston-pm mailing list
[email protected]
http://mail.pm.org/mailman/listinfo/boston-pm