3

我有一个名为master.pl. 我有一个二维数组,名为@inputarray.

我需要将二维数组值传递master.pl给另一个名为child.pl的程序并访问child.pl.

我已经尝试了很多,但我无法取消引用child.pl.

你能帮我么?

大师.pl

system "start perl child.pl $appl $count @inputarray";

孩子.pl

($appl, $count, @inputarray) = @ARGV;

for (my $k = 0; $k < $count + 1; $k++) {
    for (my $m = 0; $m < 6; $m++) {
        print "$inputarray[$k][$m] ";
    }
    print "\n";
}
4

3 回答 3

2

方法一:

看看标准模块Data::Dumper,它非常适合你想要的东西。

使用 Data::Dumper 将数据结构保存在临时文件中,然后在第二个脚本中读取它。

方法二:

使用Storable将数组存储在第一个脚本中并从其他脚本中检索它。

编辑(在您提供代码之后):

看到你可以像这样访问数组

大师.pl

#!/usr/local/bin/perl
use strict;
use warnings;
use Storable;
my @inputarray = ([1, 2, 3], [4, 5, 6], [7, 8, 9]);
store (\@inputarray, "/home/chankey/child.$$") or die "could not store";
system("perl", "child.pl", $$) == 0 or die "error";

孩子.pl

#/usr/local/bin/perl
use strict;
use warnings;
use Storable;
use Data::Dumper;
my $parentpid = shift;
my $ref = retrieve("/home/chankey/child.$parentpid") or die "coudn't retrieve";
print Dumper $ref;
print $$ref[0][0]; #prints 1

输出

$VAR1 = [
          [
            1,
            2,
            3
          ],
          [
            4,
            5,
            6
          ],
          [
            7,
            8,
            9
          ]
        ]; #from Dumper
  1 #from print $$ref[0][0]

正如您从转储中看到的,您已经收到了@inputarrayin $ref。现在以您想要的方式使用它。

于 2013-06-13T08:11:13.720 回答
1

检查Storable是否有任何类型的 perl 数据序列化/反序列化。

为了在 POSIX 系统上的进程之间传递数据,我使用命名管道,为了更好地与 Windows 兼容,您可以使用临时文件,使用 File::Temp。

于 2013-06-13T08:46:51.073 回答
1

您可以使用匿名管道,它在 UNIX 和 Windows 上的工作方式相同(我假设您使用的是 Windows,因为start. 试试这个:

use strict;
use warnings;

my $appl = 'orange';
my @inputarray = ([0,1,2],[3,4,5],[6,7,8]);

我们不需要,您可以使用标量上下文获取数组中元素的数量,或者使用;$count获取最高索引号$#inputarray

我省略了,start因为它很难调试(控制台窗口在运行后关闭)。

my $cmd = 'perl child.pl';
open(my $pipe, '|-', $cmd) or 
    die "Unable to execte $cmd; $!";

使用 Data::Dumper 我们可以添加eval语句并减少空格的生成:

use Data::Dumper;

local $Data::Dumper::Purity = 1;
local $Data::Dumper::Indent = 0;

my $dat = Data::Dumper->new([\$appl,\@inputarray],
                            [qw($appl $inputarray)]);

print $pipe $dat->Dump();
close ($pipe);

现在对于读取管道(输入流)的孩子:

use strict;
use warnings;

my ($inp) = <STDIN>;

my ($appl, $inputarray);
eval "$inp";
print "appl = $$appl\n";

使用eval通常不受欢迎,它可能会带来安全漏洞,因此请小心使用。我认为这里是有道理的。

你的循环有点复杂,有 C 的味道。这些更 Perlish:

for my $ref (@$inputarray) {
    for my $ele (@$ref) {
        print "$ele "
    }
    print "\n"
}

YAML 更安全,因为它不需要eval,但需要安装。

于 2013-06-13T09:54:15.067 回答