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

In Perl, how do I extract out the declaration of variables into a wrapper script?

背景

我有一个名为 main.pl 的 perl 脚本,它目前处于几个分支状态,就像这样:

分支机构 1:

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

sub codeIsOtherwiseTheSame()
....

分支机构 2:

my %hash2
my $variable = "b"

sub codeIsOtherwiseTheSame()
....

分支 3

my %hash
my $variable2 = "d"

sub codeIsOtherwiseTheSame()
....

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

期望的解决方案

包装脚本 1:

 my %hash;
 my $variable = "a";
 my $variable2 = "c";
 system("main.pl");

包装脚本 2:

 my %hash2;
 my $variable = "b";
 system("main.pl");

包装脚本 3:

my %hash;
my $variable2 = "d";
system("main.pl");

Main.pl

sub codeIsOtherwiseTheSame()

问题

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

将通用代码提取到模块中,而不是脚本中。保存为例如MyCommon.pm。 从执行您需要的模块中导出函数:

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

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

然后,在各种脚本中,写

use MyCommon qw{ common_code };

common_code('a', 'b');  # <- insert the specific values here.

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

使用 perlrequired

函数可以实现像您这样的简单案例的所需行为

将常用代码放在文件中,例如common.inc文件以1;结尾(模块和包含文件的要求)

sub commonFunction {
    my $data = shift;

    print "DATA: $data\n";
}

1;

Copy/move common.inc 文件到 @INC 目录之一(可能是 site 目录最适合此用途)。

使用以下命令检查您的 perl @INC 配置设置

perl -e "print qw(@INC)"

现在您可以在用户界面脚本中重用common.inc文件

#!/usr/bin/perl

require 'common.inc';

my $a = 7;

commonFunction($a);

已经建议以.pm模块的形式放置将被多次重用的公共代码。

通过这样做,您可以更好地控制 functions/variables 可见(导出)以避免 namespace clash/collision [模块可以有 functions/variables同名].

tutorial how to create a module is available. Next natural step will be OOP programming.

图书:Object Oriented Perl

perlootut, Writing perl modules, Chapter Object Oriented Perl