Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

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

by socketdave (Curate)
on Sep 15, 2005 at 16:40 UTC ( [id://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.

Replies are listed 'Best First'.
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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://492323]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (4)
As of 2024-03-29 13:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found