Evals, quotes and backslashes problem

P

Paul Burton

I've got some code similar to this:
$a='$b="a_string"';
eval($a);
print $b;

For the above, this simply prints out "a_string".

Of course, I actually want something a little more interesting than
a_string. The output I actually want is the following string:
\$a_var

I thought I could achieve this by:
$a='$b="\\\$a_var"';
but this only produces the output:
\

I've managed to hack around this problem by generating my own special
string wherever I want a "\$" in the output, and using a string
substitution to put in the backslash:
$a='$b="\!\$a_var"'
eval($a);
$b =~ s/\!\$/\\\$/g;

which does the trick.

Is there a way of doing this without the substitution cludge, with some
clever combination of quotes and backslashes? I've tried a few things,
but nothing seems to work!

Cheers

Paul.
 
S

Stefan

Paul said:
I've got some code similar to this:
$a='$b="a_string"';
eval($a);
print $b;

For the above, this simply prints out "a_string".

Of course, I actually want something a little more interesting than
a_string. The output I actually want is the following string:
\$a_var

I think you want:

$a = '$b="\\\\\\$a_var"';

Remember that because you have two sets of quotes, the string is
subjected to two levels of interpolation once it has been eval()ed.

After the line above, $a contains:

$b="\\\$a_var"

Then, when this value is eval()ed, $b becomes

\$a_var

See?


Stefan
 
B

Bill

Stefan said:
Paul Burton wrote:
I think you want:

$a = '$b="\\\\\\$a_var"';

After the line above, $a contains:
$b="\\\$a_var"

Then, when this value is eval()ed, $b becomes
\$a_var

This is an excellent example of why doublequotes " " are often
inferior to single quotes ' ' unless variable substitution is really
needed.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top