将2D数组从一个Perl脚本传递到另一个

时间:2013-06-13 07:57:18

标签: perl

我有一个名为master.pl的Perl脚本。我有一个名为@inputarray的二维数组。

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

我已经尝试了很多但是我无法在child.pl中取消引用数组。

你能帮帮我吗?

master.pl

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

child.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";
}

3 个答案:

答案 0 :(得分:2)

方法1:

查看标准模块Data::Dumper,它是您想要的理想选择。

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

方法2:

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

修改(在您提供代码后):

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

<强> master.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";

<强> child.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]

从转储中可以看到,您已收到@inputarray中的$ref。现在按照你想要的方式使用它。

答案 1 :(得分:1)

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

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

答案 2 :(得分: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,但需要安装。