如何在我的基本 Perl 脚本中包含另一个 Perl 脚本?
\n\n我有一个主要源文件test.pl,我想config.pl在其中包含辅助 s\xc3\xb3urce 文件。
在 Perl 中实现此目的的标准方法是什么?
\n(我猜测名为config.plset config 的程序您想要在 中访问test.pl。您在问题中没有明确说明。)
一个简单的例子。如果config.pl看起来像这样:
#!/usr/bin/perl
$some_var = 'Some value';
Run Code Online (Sandbox Code Playgroud)
然后你可以写成test.pl这样:
#!/usr/bin/perl
use feature 'say';
do './config.pl';
say $some_var;
Run Code Online (Sandbox Code Playgroud)
但出于多种原因,这是一个糟糕的主意。尤其是因为当您将use strictand添加use warnings到任一文件时(并且您应该在所有Perl 代码中添加use strictand ),它就会停止工作。use warnings
那么更好的方法是什么?将您的配置转换为返回散列的正确模块(在上面的示例中我只有一个标量变量,但散列为您提供了一种在单个变量中传递多个值的方法)。一个简单的方法可能如下所示。
一个名为MyConfig.pm:
package MyConfig;
use strict;
use warnings;
use parent 'Exporter';
our @EXPORT = qw[config];
sub config {
my %config = (
some_var => 'Some value',
);
return %config;
}
1;
Run Code Online (Sandbox Code Playgroud)
还有test.pl像这样的:
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use FindBin '$Bin';
use lib $Bin;
use MyConfig;
my %config = config();
say $config{some_var};
Run Code Online (Sandbox Code Playgroud)
完成该工作后,您可以添加改进,例如%config从外部文件(可能存储在 JSON 中)解析哈希,然后允许针对不同环境(例如开发与生产)进行不同配置。
这比您当前的方法要多做一点工作,但要灵活得多。您可以使用strict和warnings。