gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:57:04 26 4
gpt4 key购买 nike

背景

我有一个名为 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()

问题

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

最佳答案

将公共(public)代码提取到模块中,而不是脚本中。将其另存为例如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.

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

关于perl - 在 Perl 中,如何将变量声明提取到包装脚本中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58701098/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com