Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re^5: why lexical variables can not be interpolated?

by kennethk (Monsignor)
on Oct 21, 2013 at 18:16 UTC ( #1059150=note: print w/ replies, xml ) Need Help??


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

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:
my %hash = (AGE => 17, ); $text =~ s/\$(\w+)/$hash{$1}/g;

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.


Comment on Re^5: why lexical variables can not be interpolated?
Select or Download Code
Re^6: why lexical variables can not be interpolated?
by lightoverhead (Monk) on Oct 21, 2013 at 18:53 UTC

    Thanks hash will work! and Thank you for your recommendations too.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1059150]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2014-08-29 11:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (280 votes), past polls