in reply to Resolving scalars in a scalar

I arrive too late and Zaxo has already posted a solution similar to mine. So instead of repeating the same thing, I have considerred Zaxo's solution and came up with an idea, this may be insane but here it goes: tokenize the input string and evaluate all perl variables, sort of a mini compiler/preprocessor. The tokeniser will be very difficult to implement, I have considered B, but got lazy. Anyway, below is my solution that will work under very specific conditions:
use strict; my $alpha = "A"; my $delta = "D"; my $theta = "T"; my @hash = qw/ Hello world /; my $test = '@hash $delta and $alpha or $theta are good'; # evaluate perl variables except bare words my $result = qq{@{[ map { m/^[\$@%]./ ? eval $_ : $_ } split/\s/,$test ]}}; print "$result\n";
And the output -
Hello world D and A or T are good

Replies are listed 'Best First'.
Re: Re: Resolving scalars in a scalar
by SavannahLion (Pilgrim) on Oct 30, 2003 at 08:35 UTC
    So after mindlessly fiddling with the eval statement, I came up with the following;
    my $alpha = "A"; my $delta = "D"; my $test = "$delta and $alpha"; eval "\$test = \"$test\""; print "$test";
    Is that... right?

    Is it fair to stick a link to my site here?

    Thanks for you patience.

      Ummm, because your $test is quoted inside double quote, your $test = "D and A" even before you go into the eval, so the eval had no effect.

      Change the code slightly as follows -
      my $alpha = "A"; my $delta = "D"; my $test = '$delta and $alpha'; eval "\$test = \"$test\""; print "$test";
      and yes, it will work this time, because the code is equivalent to -
      my $alpha = "A"; my $delta = "D"; my $test = '$delta and $alpha'; $test = "$delta and $alpha"; print "$test";
      Where the variable $test inside double quote " " has been expanded by the perl interpreter to the value of $test before going into eval