in reply to Re^2: why lexical variables can not be interpolated?
in thread why lexical variables can not be interpolated?
e Evaluate the right side as an expression.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
ee Evaluate the right side as a string then eval the result.
What I've changed:$text =~ s/\$(\w+)/$$1 * 2/egx; #I tried to double the age and succee +ded!
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: why lexical variables can not be interpolated?
by lightoverhead (Pilgrim) on Oct 21, 2013 at 17:42 UTC | |
by SuicideJunkie (Vicar) on Oct 21, 2013 at 18:25 UTC | |
by lightoverhead (Pilgrim) on Oct 21, 2013 at 18:54 UTC | |
by kennethk (Abbot) on Oct 21, 2013 at 18:16 UTC | |
by lightoverhead (Pilgrim) on Oct 21, 2013 at 18:53 UTC |