【问题标题】:Perl: calling another_script.pl with parameters from script.pl and w/o system,backticks and modulesPerl:使用 script.pl 中的参数调用 another_script.pl 并且没有系统、反引号和模块
【发布时间】:2010-09-16 10:56:42
【问题描述】:

我有两个脚本和两个 conf 文件(实际上也是 perl 脚本):

conf1.pl

@some_array = ({name =>"orange", deny = > "yes"},
               {name =>"apple", deny = > "no"});

conf2.pl

@some_array = ({name =>"male", deny = > "yes"},
               {name =>"female", deny = > "no"});

脚本.pl

#!/usr/bin/perl -w
use strict;
our %deny = ();
call_another_script.pl_somehow_with_param conf1.pl
call_another_script.pl_somehow_with_param conf2.pl
foreach my $key (%deny) {
    print $deny{$key},"\n";
}

另一个脚本.pl

#!/usr/bin/perl -w
my $conf_file = shift;
do $conf_file;
foreach my $item (@some_array) {
    print $item->{name},"\n";
    if (defined $deny) {
       $deny{$item{name}}++ if $item{deny} eq "yes";
    }
}

我想用 script.pl 中的 conf 文件名调用 another_script.pl,这样 %deny 将在 another_script.pl 中可见。而且我不想使用 Perl 模块,我想将脚本放在单独的文件中。 例如

./another_script.pl conf2.pl

./脚本

【问题讨论】:

  • "我想做某事,但我明确不想使用 Perl 的特性来做这件事。但我不想解释为什么我要强加这样一个任意的约束。”

标签: perl call


【解决方案1】:

这个问题正是模块旨在解决的问题。您要问的类似于“我如何在没有if 的情况下有条件地执行代码?”。我们可以告诉你怎么做,但这不是一个好主意。

conf1.pl

#!/usr/bin/perl

use strict;
use warnings;

our @a = (1 .. 10);

conf2.pl

#!/usr/bin/perl

use strict;
use warnings;

our @a = ("a" .. "j");

master.pl

#!/usr/bin/perl

use strict;
use warnings;

our %deny;
do "conf1.pl";
do "child.pl";
do "conf2.pl";
do "child.pl";

use Data::Dumper;
print Dumper \%deny;

child.pl

#!/usr/bin/perl

use strict;
use warnings;

our %deny;
our @a;

for my $item (@a) {
    $deny{$item}++;
}

【讨论】:

  • 当他们要求错误的东西时,就会出现回答他们所问问题的奖励问题。太恶心了,你为什么要给他看这个?
  • @masonk 我也打算向他展示如何正确地做到这一点,以便他看到其中的不同之处,但我还没有时间回去修复它。
  • 我只想像在 bash 中那样:编写一个脚本,另一个脚本 - 每个都独立工作并接受参数。当需要解决更一般的问题时,只需从另一个脚本调用一个脚本。不用担心范围和模块。并且每个脚本都可以独立执行。比如:master #!/bin/sh VARIABLE=value export VARIABLE ./child child #!/bin/sh echo $VARIABLE
  • @gapsf 然后使用bash。 Perl 不是bash。如果你试图强迫 Perl 像 bash 这样你会错过所有让 Perl 比 bash 更好的东西。
【解决方案2】:

http://www.serverwatch.com/tutorials/article.php/1128981/The-Perl-Basics-You-Need-To-Know.htm

使用 Strict Pragma 使变量全局化 首先你使用:

use strict;

然后你使用:

use vars qw( %hash @array);

这将命名变量声明为当前包中的全局变量 包裹。它们可以在同一个文件和包中被引用 不合格的名称;并在不同的文件/包中具有完全合格的 名字。 这就是我所需要的!

【讨论】:

    猜你喜欢
    • 2014-01-21
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多