http://www.perlmonks.org?node_id=1059147


in reply to Re^2: why lexical variables can not be interpolated?
in thread why lexical variables can not be interpolated?

As described in s/PATTERN/REPLACEMENT/msixpodualgcer in perlop,
e Evaluate the right side as an expression.
ee Evaluate the right side as a string then eval the result.
The reason $text =~ s/(\$\w+)/$1/eeg; works is the regular expression stores $AGE (string literal) in $1. For the substitution, $1 is evaluated to return $AGE, and then $AGE 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
$text =~ s/\$(\w+)/$$1 * 2/egx; #I tried to double the age and succee +ded!
What I've changed:
  1. I used an explicit dereference $$1, which could also be expressed as ${$1}
  2. 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 AGE; otherwise it would assume you are looking for a variable with an explicit dollar sign in its name.
  3. I changed the code to eval only once.

I realize that this is a learning exercise, but for reference if I were going to do this kind of templating, I would use sprintf in something like:

$AGE = 17; $tmpl = 'I am %s years old'; # note single quotes $text = sprintf $tmpl, $AGE * 2; # print I am 17 years old

#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.