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

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.

tel2


Comment on Re: Executing a string as a Perl command
Select or Download Code
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;

        how?
        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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (7)
As of 2015-07-06 10:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (71 votes), past polls