在Perl中,如何将变量的声明提取到包装脚本中?

isa*_*bob 2 perl wrapper

背景

我有一个perl脚本,称为main.pl,在清晰的情况下,当前处于多个分支状态,如下所示:

分支1:

my %hash
my $variable = "a"
my $variable2 = "c"

sub codeIsOtherwiseTheSame()
....
Run Code Online (Sandbox Code Playgroud)

分支2:

my %hash2
my $variable = "b"

sub codeIsOtherwiseTheSame()
....
Run Code Online (Sandbox Code Playgroud)

分公司3

my %hash
my $variable2 = "d"

sub codeIsOtherwiseTheSame()
....
Run Code Online (Sandbox Code Playgroud)

现在,脚本的每个分支都具有相同的代码。唯一的区别是声明的变量的种类及其初始化值是什么。我要做的是将这些不同的变量提取到包装脚本中(对于每个变体),这样就不必更改主脚本了。我这样做是因为有几个用户将使用此脚本,但是根据他们的用例,它们之间只有很小的差异。因此,我希望每种用户都有自己的简化界面。同时,我希望主脚本在被调用后仍能意识到这些变量。以下是我想要的示例:

所需解决方案

包装脚本1:

 my %hash;
 my $variable = "a";
 my $variable2 = "c";
 system("main.pl");
Run Code Online (Sandbox Code Playgroud)

包装脚本2:

 my %hash2;
 my $variable = "b";
 system("main.pl");
Run Code Online (Sandbox Code Playgroud)

包装脚本3:

my %hash;
my $variable2 = "d";
system("main.pl");
Run Code Online (Sandbox Code Playgroud)

Main.pl

sub codeIsOtherwiseTheSame()
Run Code Online (Sandbox Code Playgroud)

如何提取包装器脚本以获得上面想要的组织和行为?

cho*_*oba 6

将通用代码提取到模块而不是脚本中。将其另存为MyCommon.pm。从执行所需功能的模块中导出功能:

package MyCommon;
use Exporter qw{ import };
our @EXPORT = qw{ common_code };

sub common_code {
    my ($var1, $var2) = @_;
    # Common code goes here...
}
Run Code Online (Sandbox Code Playgroud)

然后,用各种脚本编写

use MyCommon qw{ common_code };

common_code('a', 'b');  # <- insert the specific values here.
Run Code Online (Sandbox Code Playgroud)

有更高级的方法,例如,您可以使用“面向对象”:从特定的值构造一个对象,然后运行实现通用代码的方法-但是对于简单的用例,您可能不需要它。