note
kennethk
As described in [doc://perlop#s/PATTERN/REPLACEMENT/msixpodualgcer] in [doc://perlop],
<blockquote>
e Evaluate the right side as an expression.
<br/> ee Evaluate the right side as a string then [doc://eval] the
result.
</blockquote>
The reason <c>$text =~ s/(\$\w+)/$1/eeg;</c> works is the regular expression stores <c>$AGE</c> (string literal) in <c>$1</c>. For the substitution, <c>$1</c> is evaluated to return <c>$AGE</c>, and then <c>$AGE</c> is evaluated to return 17. Your second code attempts to multiply the string literal $AGE by 2, not the value of it - you've got your order of operations off. You could accomplish this using an explicit dereference rather than invoking eval twice, like
<c>
$text =~ s/\$(\w+)/$$1 * 2/egx; #I tried to double the age and succeeded!
</c>
What I've changed:
<ol>
<li>I used an explicit dereference <c>$$1</c>, which could also be expressed as <c>${$1}</c>
<li>I changed the pattern so that the sigil is replaced, but is not part of the pattern. This is necessary because $$1 attempts to access the scalar variable named <c>AGE</c>; otherwise it would assume you are looking for a variable with an explicit dollar sign in its name.
<li>I changed the code to [doc://eval] only once.
</ol>
<p>I realize that this is a learning exercise, but for reference if I were going to do this kind of templating, I would use [doc://sprintf] in something like:
<c>
$AGE = 17;
$tmpl = 'I am %s years old'; # note single quotes
$text = sprintf $tmpl, $AGE * 2; # print I am 17 years old
</c>
<!-- Node text goes above. Div tags should contain sig only -->
<div class="pmsig"><div class="pmsig-712372">
<hr />
<p>#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.</p>
</div></div>
1059136
1059145