good chemistry is complicated, and a little bit messy -LW |
|
PerlMonks |
Re^5: why lexical variables can not be interpolated?by kennethk (Abbot) |
on Oct 21, 2013 at 18:16 UTC ( [id://1059150]=note: print w/replies, xml ) | Need Help?? |
It seems to me that it's impossible to use /e to solve this situation when variable is lexical scoped.There's no way around that using symbolic variables because symbolic variables only access package variables. The easiest drop in would be using a hash, which might look like:
This has the advantage of removing a bunch of misdirection and potential security complications. If you wanted to make key misses fatal, you can use lock_hash in Hash::Util; of course, your symbolic reference code doesn't die on misses. Yes, sprintf will work for this case as we know it's a number; but in other cases we may not know if $AGE holds a numeric value. sprintf works for any string. Note I use %s for string replacement; numerical replacement would be %d. Obviously the multiplication only works if $AGE is a number, but that's sort of given. If you are learning this with an eye toward production code, please read Why it's stupid to use a variable as a variable name. Also, there are a large number of real templating packages out there, such as HTML::Template for simple projects and Template::Toolkit for more complex ones. #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.
In Section
Seekers of Perl Wisdom
|
|