将一个 2D 数组从一个 Perl 脚本传递到另一个 [英] Passing a 2D array from one Perl script to another

查看:47
本文介绍了将一个 2D 数组从一个 Perl 脚本传递到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Perl script called master.pl. I have a 2D array in that called @inputarray.

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

I need to pass the 2D array values from master.pl to another program called child.pl and access the data in the child.pl.

我尝试了很多,但我无法取消引用 child.pl 中的数组.

I have tried a lot but I'm not able to dereference the array in child.pl.

你能帮我吗?

ma​​ster.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";
}

推荐答案

方法一:

看看标准模块 Data::Dumper,它非常适合你想要.

Have a look at the standard module Data::Dumper, it's ideal for what you want.

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

Save your data structure in a temporary file using Data::Dumper and then read it in your second script.

方法 2:

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

Using Storable to store array in first script and retrieve it from other.

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

看你可以像这样访问数组

See you can access the array like this

ma​​ster.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]

正如您从转储中看到的,您已经在 $ref 中收到了 @inputarray.现在按照您想要的方式使用它.

As you can see from dump, you've received the @inputarray in $ref. Now use it the way you want.

这篇关于将一个 2D 数组从一个 Perl 脚本传递到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆