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

Re: Executing a string as a Perl command

by tel2 (Pilgrim)
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 drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2018-06-23 21:53 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (125 votes). Check out past polls.