如何将数组和哈希从一个脚本传递到另一个脚本?

时间:2014-01-24 05:58:36

标签: perl

我尝试使用以下代码调用另一个脚本

system("perl sample.pl");

如何将值,数组和哈希传递给另一个脚本以及如何在sample.pl中获取这些值?

3 个答案:

答案 0 :(得分:1)

我不确定这是否是最佳方法,但您可以使用Data::Dumper并阅读stdin中的数据。

test.pl

#!/usr/bin/perl
use strict;
use warnings;
use FileHandle();
use Data::Dumper();

my %data = ( 
    key => 'value',
    arr => [ 0..5 ],
);

my $fh = FileHandle->new('| ./sample.pl') or
    die "Could not open pipe to './sample.pl': $!\n";
print $fh Data::Dumper->Dump([\%data], [qw(data)]);
$fh->close();

sample.pl

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper();

my $str = do { local $/; <STDIN> };
my $data;
eval $str;
if ($@) {
    die "Error in eval: $@\n";
}
$data->{key} = 'new value';
print Data::Dumper->Dump([$data], [qw(data)]);

输出

$ ./test.pl 
$data = {
          'key' => 'new value',
          'arr' => [
                     0,
                     1,
                     2,
                     3,
                     4,
                     5
                   ]
        };

答案 1 :(得分:1)

您可以将它们作为命令行参数传递,其类型为cmd行值之一

然后检查包含类型的cmd-line值,该值将在@ARGV中,如下所示:

mainscript.pl

use strict;
use warnings;

# Variable
my $ele = 10;
system("perl sample.pl $ele varval");

# Array
my @arr = (1,2,3);
system("perl sample.pl @arr arrval");

# Hash
my %h = (
    'a' => 1,
    'b' => 2
);
my @a = %h;
system("perl sample.pl @a hashval");

Sample.pl

use Data::Dumper;
print("\nIn sample\n");

if($ARGV[-1] eq 'varval')
{
    print("\nIts var\n");
    delete($ARGV[-1]);
    print($ARGV[0]);
}
elsif ($ARGV[-1] eq 'arrval')
{
    print("\nIts array\n");
    delete($ARGV[-1]);
    @temparr = @ARGV;
    print(@temparr);
}
elsif ($ARGV[-1] eq 'hashval')
{
    print("\nIts hash\n");
    delete($ARGV[-1]);
    my %h1 = @ARGV;
    print(Dumper(\%h1));
}

输出:

  

D:\ perlp&gt; perl mainscript.pl

     

样本

     

其var 10

     

样本

     

其数组123

     

样本

     

其哈希值$ VAR1 = {             'a'=&gt; '1',             'b'=&gt; '2'           };

     

d:\ perlp&GT;

答案 2 :(得分:0)

为什么要通过STDIN传递它们?我认为在开始system调用之前编写一个简短文件会更容易。并使用其他脚本读取该文件。当你想创建一个动态文件名时(当你有多次执行时),你可以通过STDIN传递文件名。

即使是想要传递的复杂对象。您可以使用that进行序列化。它是一个CORE模块。

相关问题