aplonis has asked for the wisdom of the Perl Monks concerning the following question:

I would like to execute Perl commands contained in a string. The string in question may be any arbitrary Perl code as typed by user into a Tk Text widget.

This is for a data editor, so commands must execute in same main package as for the Tk widget which called it so as to act upon same vars, arrays and hashes as exist in said package.

I have tried 'exec' but it seems to execute independently, as if in some wholly different package. In Forth all that would be required is to make the string executable and call it. How would one accomplish such a feat in Perl?

Replies are listed 'Best First'.
Re: Execute commands in a string
by etcshadow (Priest) on Aug 15, 2004 at 19:38 UTC
    my $sourcepackage = caller; eval "package $sourcepackage; $code"; print "Error in eval: $@" if $@ ne '';
    Change the print to be whatever you want to do if there are errors (syntax or runtime) in the string of $code.
    ------------ :Wq Not an editor command: Wq

      That was it! Just the trick, Thanks a heap.

Re: Execute commands in a string
by Aristotle (Chancellor) on Aug 15, 2004 at 19:24 UTC

    Enter eval.

    Makeshifts last the longest.

Re: Execute commands in a string
by saintmike (Vicar) on Aug 15, 2004 at 19:26 UTC
    Use eval "perl code" to execute arbitrary Perl code and prepend the string with "package Whatever;" to enforce it being evaluated in the given package.
      Enforce? I don't think so :)
      $code = 'package Enforce::NOT; sub you; sub cannot;'; eval "package Whatever; $code";

      MJD says "you can't just make shit up and expect the computer to know what you mean, retardo!"
      I run a Win32 PPM repository for perl 5.6.x and 5.8.x -- I take requests (README).
      ** The third rule of perl club is a statement of fact: pod is sexy.

Re: Execute commands in a string
by CountZero (Bishop) on Aug 15, 2004 at 19:27 UTC
    Did you consider the use of eval?

    But be aware of the security risks eval can bring.

    CountZero

    "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law