shan_emails has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

Is their any option for variable interpolation

my code is as follows
use strict; our $aa=10; our $vv=20; my $x='asdf <add>$aa + $vv</add> asdf '; $x =~ s/<add>(.*?)<\/add>/process($1)/gsei; print $x; sub process(){ my $var = shift; print $aa; print $vv; print $var; #here i need to variable interpolate the $var string }


Thanks in advance
Shanmugam A.

Replies are listed 'Best First'.
Re: variable interpolation
by GrandFather (Saint) on Feb 12, 2009 at 20:18 UTC

    Why? You have already asked at least twice about symbolic reference related issues. I suspect you have settled on what is probably a fundamentally wrong approach to solving a problem and as a result are asking a slew of XY questions.

    Please tell us what your bigger problem is so that we can stop giving you bad and/or contradictory advice. Generally any solution requiring symbolic references or string eval are bad (not all, but most) and there are better ways of solving the problem.


    True laziness is hard work
      Hi, I have a line read in perl from a file that itself is a source code for languages like c/sv etc. The variable containing this line contains special characters like %d. When i print this line to another file, the %d is evaluated and a 0 is getting printed. How do i overcome this and tell perl to strictly not interpolate/evaluate any contents of this variable and simply print it as is ! ~Pushkar

        Show us some sample code! I can think of a number of ways you might get that result, and none of them are good technique.

        Oh, and always use strictures (use strict; use warnings;). You are probably doing something silly that strict would tell you about.


        True laziness is hard work
Re: variable interpolation
by jethro (Monsignor) on Feb 12, 2009 at 15:38 UTC

    Yes, there are symbolic references.

    > perl -e ' $vv='a'; $var='vv'; print $$var;'; a

    You also might use eval() to construct an access to the variable. Preferable if $var might sometimes contain values that are not valid variable names like '('. Then eval() can trap the error.

    > perl -e ' $vv='a'; $var='vv'; eval "print \$$var;" ' a
Re: variable interpolation
by MidLifeXis (Monsignor) on Feb 12, 2009 at 15:39 UTC

    I believe that $var, even if interpolated, will only give you the string '10 + 20'. I think what you are looking for is an eval(). However, please be careful about what you eval. For example, in your add tags, you may want to be more strict in what matches.

    --MidLifeXis

      ok thanks for your information --Shanmugam A.