Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: How to do that with eval ?

by davido (Cardinal)
on Apr 10, 2004 at 07:40 UTC ( [id://344098]=note: print w/replies, xml ) Need Help??


in reply to How to do that with eval ?

One problem is that you're ignoring double-quoteish variable interpolation.

Consider the following:

my $value = 100; my $string = "$value"; print $string, "\n"; __OUTPUT__ 100

Ok, here's the problem. What you just witnessed is $value being interpolated as a variable into a string, and assigned to $string. Seems harmless. But it can easily get you into trouble.

my $var = "Hello world!"; my $evalcode = "print $var, qq/\n/;"; eval $evalcode or print "There was a problem:\n$@\n"; __OUTPUT__ There was a problem: syntax error at (eval 1) line 1, near "!,"

The problem was that before eval got a chance to see $var, it got interpolated by the double quotes and thus was seen by eval as a literal string rather than a variable. The code that eval saw was:
print Hello world, qq/\n/;

See the error? You wanted eval to see
print $var, qq/\n/;. Instead, you got an unquoted literal string that looked a lot like a bunch of garbage to Perl.

The situation can be remedied by either using single quotes, or by escaping your double-quoted variables so that eval gets them uninterpolated. It can be tricky deciding which option to use. ...but that's the nature of eval... a little tricky. ;)


Dave

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://344098]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (2)
As of 2024-04-25 02:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found