in reply to Run Perl from within Perl
As has been pointed out, there are ways. However, there is a deeper question here: why.
I have a very hard requirement on my team to do all real work in modules. This has made things much easier to integrate into multiple scripts (I have many tasks to perform which are used in multiple scripts, and many others that are unique to a certain script, but because of the modularity of the code, I can always use them in other places). Cutting and pasting the code into a module doesn't necessarily give you this benefit - it's thinking of being in a module that does. You no longer think it's ok to chdir to another directory without chdir'ing back, for example. You think long and hard about affecting global variables, such as %ENV or @ARGV or [$@%]::* (anything in main's namespace).
It has a side effect that doesn't help us, but can help others (though not your specific request here): there is no reliable way to reuse the current perl interpreter in a subprocess. $^X may not be perl (if you're in an interpreter that is embedded in something else, such as apache, emacs, or vim). Fork may have unintended consequences (DBI connections are fragile if you're not defensive about this, you may accidentally log to the same logfile as the parent process - trust me, this wreaks havoc on the logfiles - I've fought that battle already!). Much nicer to have a self-contained module which is aware of how to play nice with other perl code than to try to shoe-horn not-nice code into your code and have to live with the side-effects.
Now, if you can't get this other code into a module that is easy to call, you may still be best off using a subprocess. If you think that's not viable, you will want to save as much state as possible (you decide which ones you care about) before eval'ing or do'ing the perl script, including, but not limited to, current working directory, %ENV, $_, and many other globals. Also beware of redefinitions of functions - loading a new perl script into the main package may clobber any subs you have in main. So, you may want to move all your code into a module to keep it in a unique namespace.
"Good practice" is whatever gets the job done as cleanly as allowed. As much as it can be avoided, this is not good practice. But, when it cannot be avoided, do it. To me, this is like the "goto" in C: it is bad practice to use it when it can be avoided (use if, while, for, etc., instead). But, when it cannot be avoided, then it is good practice. The problem is that it often takes a certain amount of experience to tell where that line is.
|
|---|