使用与父脚本相同的@INC调用脚本

时间:2016-09-19 07:49:56

标签: perl

我想使用system ($script)do $script调用外部脚本。在我的@INC中,我有一些我导入的特定模块。如何调用$script并将其转移到同一个@INC

Script1.pm

#importing some libs
#code
$script = "path_to_script";

system ($script);

Script2.pm

use LibFromScript1@INC;

我得到了错误:

  

无法在@INC中找到LibFromScript1 ...

3 个答案:

答案 0 :(得分:2)

您可以do $script;严格回答您的问题,但建议的方法是将您的常用程序逻辑分离到模块中,并use/require

答案 1 :(得分:2)

最简单的方法可能是设置PERL5LIB环境变量。这将为子进程的@INC数组

添加一个目录列表

您的代码看起来像

$ENV{PERL5LIB} = join ':', @INC;

system $script;

这样做的缺点是标准目录也会添加到@INC。它不应该导致任何问题,但如果您在那时知道它们,最好将PERL5LIB设置为自定义目录。

另请注意,如果您在污点标记下运行,perl将忽略PERL5LIB

答案 2 :(得分:0)

您可以使用Storable@INC保存在文件中,然后在其他脚本中选择它。

例如,您可以执行以下操作。

<强> test.pl

#!/usr/bin/perl
use strict;
use warnings;
use Storable;
store (\@INC, "test2.dump") or die "could not store";
system("perl", "test2.pl", $$) == 0 or die "error";

<强> test2.pl

#!/usr/bin/perl
use strict;
use warnings;
use Storable;
use Data::Dumper;
my $parentpid = shift;
my $ref = retrieve("test2.dump") or die "couldn't retrieve";
print Dumper $ref;

@INC test2.pl作为$ref后,您可以修改@INC中的test2.pl以从$ref获取内容。

相关问题