Beefy Boxes and Bandwidth Generously Provided by pair Networks Russ
There's more than one way to do things
 
PerlMonks  

Re: Probably an easy one - store command in variable.

by socketdave (Curate)
on Sep 15, 2005 at 16:40 UTC ( #492323=note: print w/ replies, xml ) Need Help??


in reply to Probably an easy one - store command in variable.

This should do what you're looking for:

eval $command;

By the way, eval traps otherwise fatal errors, so pay attention to what's happening with the code being eval'd.

Update:Thanks to everyone for pointing out the scoping and performance problems with eval. It just 'popped in there' like the Stay-Puffed marshmallow man.


Comment on Re: Probably an easy one - store command in variable.
Download Code
Re^2: Probably an easy one - store command in variable.
by Codon (Friar) on Sep 15, 2005 at 16:54 UTC
    Just know that string eval can be costly (starts a new Perl interpreter) and potentially dangerous (you aren't using tainted user input to build this string are you?; run this with perl -T to find out for sure).

    Are you running this under use strict;? If so, then you will have some problems with my @returnsting. Specifically, you will need to have @returnstring declared before your eval to use it later. That means when you eval "my @returnstring = ...", you will create lexical variable within the scope of the eval that will mask the @returnstring that you declared outside of the eval scope. To solve this, simply remove the my from the string that you build.

    Ivan Heffner
    Sr. Software Engineer, DAS Lead
    WhitePages.com, Inc.
      Just a nit-pick; string eval does not start a new perl interpreter, although it does need to compile the $string every time the eval statement is executed, which usually makes it slow compared to alternative strategies.

      There are also some subtle issues and bugs with eval $string and scoping, but you're unlikely to run into them if you use eval $string sparingly. update: as nobull states: in this particular case, you've ran into one such issue: a lexical variable declared inside a string eval is not available outside of the eval statement :-)

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (4)
As of 2014-04-19 23:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (485 votes), past polls