The problem is that you can't just "put things in double quotes" at runtime.
Let's assume that there's a string $string which I've just read from a file. The string contains 'abc $var def'. What I want is: Treat this string as if there were double quotes around it and interpolate any variables that are in it. Just as if it was "abc $var def" (double quotes) in a Perl program.
The previous postings have shown that this is not a straight-forward task.
So far, the only way I found to make this work (still with limitations) is to use something like this:
my $x = "foo";
my $y = 'abc $x def\\/';
escape_slashes($y);
$y = eval "qq/$y/";
unescape_slashes($y);
print "y=$y\n";
sub escape_slashes {
$_[0] =~ s#(\\|/)#\\\\$1#g;
}
sub unescape_slashes {
$_[0] =~ s#(\\\\|\\/)#substr($1, 1, 1)#eg;
}
which just puts double quotes around the string, eval()s it and makes sure none of the characters in the string messes with the surrounding double quotes (or their qq// delimiter equivalents).
The ideal solution would be to step down into the perl machine room and replicate exactly what happens during runtime if your program contains a string in double quotes:
my $result = "abc $var def";
does exactly the right thing, it interpolates correctly. So, who can show me that entrance to the machine room?
Please don't just brush off this question by saying "Why on earth would you do that?". It's not about best programming practices. It's about language completeness.
It's possible to do eval "perl code" in order to evaluate Perl code. Is it really necessary to resort to the kludge of saying eval "\"interpolate_this\"" (and deal with the resulting escape problems) to have a string interpreted as if it was inside double quotes? |