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

I have a program where I let the user specify some expressions using variables in the program. For now I want to use strings like "foo has the value $foo" and see the value of $foo printed out. My code looks like this:
sub fun{ return sub {return 'foo has value $foo'); } ... $coderef = fun; $foo = 7; $str = &$coderef;
Of course, $str is "foo has the value $foo". I'd like to do "variable interpolation" on $str. I thought eval might do that, but is unhappy trying to do just that. I believe that there is a simple answer, but it is one of those days when the mind gets totally fogged...

When I tried double quotes around the string, it tried to evaluate $foo (which was undefined) and created a closure with the string having an undefined value.

As always, any help is appreciated,
--traveler

Replies are listed 'Best First'.
Re: Delaying interpolation
by meonkeys (Chaplain) on Aug 07, 2001 at 04:22 UTC
    How's this?
    use strict; my $foo = 'nothing yet'; sub fun { return sub { return "foo has value $foo" } } my $coderef = fun(); $foo = 7; my $str = &$coderef; print "$str\n";
Re: Delaying interpolation
by abstracts (Hermit) on Aug 07, 2001 at 04:26 UTC
    Hello

       eval EXPR
       eval BLOCK
          In the first form, the return value of EXPR is
          parsed and executed as if it were a little Perl
          program.
    
    So, to return "foo has value $foo" after interpolation, you can do:
    my $foo = 7; my $str = eval '"foo has $foo"'; print $str;
    Notice the additional double quotes inside the single quotes. This makes eval evals
    "foo has $foo"
    and returns the resulting string. If you don't include the additional quotes, eval evals
    foo has $foo
    which is not what you want.

    Hope this helps,,,

    Aziz,,,

Re: Delaying interpolation
by chipmunk (Parson) on Aug 07, 2001 at 06:39 UTC
Re: Delaying interpolation
by traveler (Parson) on Aug 07, 2001 at 05:01 UTC
    I tried each and they worked. Thanks!