Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

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

by kennethk (Abbot)
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.

Replies are listed 'Best First'.
Re^6: why lexical variables can not be interpolated?
by lightoverhead (Pilgrim) on Oct 21, 2013 at 18:53 UTC

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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1059150]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2018-05-26 06:58 GMT
Find Nodes?
    Voting Booth?