Replacing variable names with values via reference in regexp



Hi,

I am trying to make a small template-like expansion in my code, though
I could fetch variable values via a reference but looks like I am
stuck. A sample code like this:

$var = "variable";
$a = 'This is a string with a <%=var%>!'; # single-quoted for no
variable substitution
$a =~ s/<%=([a-z]+)%>/{ $v=$1; $$v; }/eg;
print $a;

works. However, when I put it into larger code like this:

#! /usr/bin/perl -w
use strict 'vars';

my $template1 = 'This is a string with a <%=var%>!';
my $template2 = 'This is a string with a <%=main::var%>!';
my $var = 'variable';
print tmplParse($template1)."\n";
print tmplParse($template2)."\n";

sub tmplParse {
my $tmpl = shift;
my $v;
$tmpl =~ s/<%=([a-z:0-9_]+)%>/{ $v=$1; warn "\$v is now '$v'\t \$\$v
is '$$v'\n"; $$v; }/eg;
return $tmpl;
}

All I keep on getting is

Use of uninitialized value in concatenation (.) or string at
template.pl line 13.

(which is where substitution should happen)

If my reading is correct, it is unable to find a reference to either
$var or $main::var. But even if I define a local $var and set its
value inside of tmplParse, I still get the same error.

Any ideas, pointers, suggestions?

Thanks,
Andrei

.



Relevant Pages

  • Re: window object
    ... Within a script, every reference to an object amounts to two ... calls from the scripting engine to the DHTML Object Model. ... var sText = document.all.div1.innerText; ...
    (comp.lang.javascript)
  • Re: can you add whole types of elements to addEventListener? if not, how else to achieve the efffect
    ... var eventTargetRef = e.target; ... the proprietary `document' reference (where for the latter there is alas ... caused the event is an implementation of W3C DOM Level 2 Event's ... proprietary event-handling property is available. ...
    (comp.lang.javascript)
  • Re: RTL and offsetLeft in IE 6
    ... var body = document.body, ... the return value may as well not be a reference to a host object. ... property access below, so it needs to be tested or the property access could ...
    (comp.lang.javascript)
  • Re: Reference to a reference?
    ... What's the point of storing a null reference in a HashSet? ... foreach (var item in collection) ... There is situation where late initialization is necessary, so I initially set it to null, but I know later at some time this object will eventually get initialized so I want the set to use the initialized object instead - hence the creation of Referenceclass. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: pointer syntax
    ... > really passing a reference (which is like an old-school pointer, ... > a copy of the primitive's value and passing that. ... build them yourself with pointers. ... mean a var parameter, write a var parameter. ...
    (comp.lang.pascal.delphi.misc)