How to run “source” command (Linux) from a perl sc

2019-08-11 20:38发布

问题:

I am trying to source a script from a Perl script (script.pl).

system ("source /some/generic/script");

Please note that this generic script could be a shell, python or any other script. Also, I cannot replicate the logic present inside this generic script into my Perl script. I tried replacing system with ``, exec, and qx//. Each time I got the following error:

Can't exec "source": No such file or directory at script.pl line 18.

I came across many forums on the internet, which discussed various reasons for this problem. But none of them provided a solution. Is there any way to run/execute source command from a Perl script?

回答1:

In bash, etc, source is a builtin that means read this file, and interpret it locally (a little like a #include).

In this context that makes no sense - you either need to remove source from the command and have a shebang (#!) line at the start of the shell script that tells the system which shell to use to execute that script, or you need to explicitly tell system which shell to use, e.g.

system "/bin/sh", "/some/generic/script";

[with no comment about whether it's actually appropriate to use system in this case].



回答2:

You can't. source is a shell function that 'imports' the contents of that script into your current environment. It's not an executable.

You can replicate some of it's functionality by rolling your own - run or parse whatever you're 'sourcing' and capture the result:

 print `. file_to_source; echo $somevar`;

or similar.