Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

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 all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (6)
As of 2017-11-21 19:53 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (310 votes). Check out past polls.