Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Re: Executing a string as a Perl command

by tel2 (Monk)
on May 10, 2011 at 01:59 UTC ( #903883=note: print w/replies, xml ) Need Help??

in reply to Executing a string as a Perl command

Thanks guys,

Before creating this thread, I had made the mistake of testing it like this:

perl -e '$cmd = "$var1 = 5;";eval $cmd;print $var1'

but of course that failed because of the double quotes.  So now I've changed it to this:

perl -e '$cmd = q[$var1 = 5;];eval $cmd;print $var1'

which works just like a bought one.

Thanks for your help.


Replies are listed 'Best First'.
Re^2: Executing a string as a Perl command
by johnpeterdinesh (Initiate) on May 10, 2011 at 09:22 UTC

    Please try below code

    my $cmd = '$var1 = 5'; eval "$cmd"; print $var1;
      Why the double quotes? eval $cmd; works fine, no need for an additional stringification.
      1. ...and your point (aside from the fact that your code prints "5") is...?
      2. ... and this is better than

        my $var1 = 5; print $var1;

        This short illustrative example has $cmd set inline, but in a real program, it could be constructed from other variables, it could be read from a user, it could be read from a file, etc.

        The question was simply how to get it to execute once it was set. The answer is eval.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2016-10-22 03:07 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (291 votes). Check out past polls.