Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Executing a string as a Perl command

by tel2 (Scribe)
on May 10, 2011 at 01:25 UTC ( #903872=perlquestion: print w/ replies, xml ) Need Help??
tel2 has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

What is a simple way to execute a string as a Perl command, in a Perl script?

For example, let's say I have a scalar assignment like this:

$cmd = '$var1 = 5;';

If I want to execute $cmd, ending up with $var1 containing 5, what's an easy way to do it, (without parsing the string, picking out the variable & value, and making the assignment with an indirect reference).  I've looked at 'eval', and other posts here, but can't find anything appropriate yet.

Thanks.
Tel2

Comment on Executing a string as a Perl command
Download Code
Re: Executing a string as a Perl command
by educated_foo (Vicar) on May 10, 2011 at 01:29 UTC
    What's wrong with "eval"?
Re: Executing a string as a Perl command
by ikegami (Pope) on May 10, 2011 at 01:34 UTC
Re: Executing a string as a Perl command
by tel2 (Scribe) on May 10, 2011 at 01:59 UTC

    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

      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?
Reaped: Re: Executing a string as a Perl command
by NodeReaper (Curate) on May 10, 2011 at 09:24 UTC

      Drop the double quotes! They are not necessary (in this case) and just slow the code down. In some cases blindly enclosing variables in quotes would lead to strange looking bugs. This is Perl, not a shell script.

      Jenda
      Enoch was right!
      Enjoy the last years of Rome.

        The "slow the code down" is so small as to be non-existent.

        xoxo,
        Andy

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://903872]
Approved by ikegami
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (7)
As of 2014-08-29 17:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (283 votes), past polls