使用系统将哈希对象从一个 perl 脚本传递到另一个

Pass a hash object from one perl script to another using system

我有以下 perl 脚本,它接收参数文件并将其存储到散列中。我想修改此哈希并将其传递给我使用系统命令调用的另一个 perl 脚本:

script1.pl

#!/usr/bin/perl -w
# usage perl script1.pl script1.params
# script1.params file looks like this:
# PROJECTNAME=>project_dir
# FASTALIST=>samples_fastq.csv

use Data::Dumper;

my $paramfile = $ARGV[0];

# open parameter file
open PARAM, $paramfile or die print $!;

# save it in a hash
my %param;
while(<PARAM>)
{
        chomp;
        @r = split('=>');
        $param{$r[0]}=$r[1];
}

# define directories
# add to parameters' hash
$param{'INDIR'} = $param{'PROJECTNAME'}.'/input';
$param{'OUTDIR'} = $param{'PROJECTNAME'}.'/output';

.... do something ...
# @samples is a list of sample names
foreach (@samples)
{
        # for each sample, pass the hash values & sample name to a separate script
        system('perl script2.pl <hash> $_');
}

script2.pl

#!/usr/bin/perl -w
use Data::Dumper;
## usage <script2.pl> <hash> <samplename>
# something like getting and printing the hash
my @string = $ARGV[0];
print @string;

如果你能帮我展示如何传递和获取散列对象(像在第二个脚本中打印散列对象这样简单的事情就可以),那么我将不胜感激。

谢谢!

您正在寻找的是一种叫做序列化的东西。由于指针和缓冲区等各种有趣的东西,很难以在进程之间传递的方式直接表示内存结构。

所以你需要把你的哈希变成足够简单的东西,以便一次性交出。

我认为三个关键选项:

  • Storable - 一个 perl 核心模块,可让您 freezethaw 用于此类目的的数据结构。
  • JSON - 基于文本的散列结构表示。
  • XML - 有点像 JSON,但略有不同 strengths/weaknesses。

您应该使用哪种取决于您的数据结构有多大。

Storable 可能是最简单的,但它不会特别便携。

还有 Data::Dumper 这也是一个选项,因为它打印数据结构。不过,一般来说,我建议它具有上述所有缺点 - 您仍然需要像 JSON/XML 一样解析它,但它也不可移植。

示例使用 Storable:

use strict;
use warnings;
use Storable qw ( freeze  );
use MIME::Base64;

my %test_hash = (
    "fish"   => "paste",
    "apples" => "pears"
);

my $frozen = encode_base64 freeze( \%test_hash );

system( "perl", "some_other_script.pl", $frozen );

通话中:

use strict;
use warnings;
use Storable qw ( thaw );
use Data::Dumper;
use MIME::Base64;

my ($imported_scalar) = @ARGV; 
print $imported_scalar;
my $thing =  thaw (decode_base64 $imported_scalar ) ;
print Dumper $thing;

或:

my %param =  %{ thaw (decode_base64 $imported_scalar ) };
print Dumper \%param;

这将打印:

BAoIMTIzNDU2NzgEBAQIAwIAAAAKBXBhc3RlBAAAAGZpc2gKBXBlYXJzBgAAAGFwcGxlcw==
$VAR1 = {
          'apples' => 'pears',
          'fish' => 'paste'
        };

JSON 做同样的事情 - 它的优点是可以作为纯文本和通用格式传递。 (大多数语言都可以解析JSON):

#!/usr/bin/env perl
use strict;
use warnings;
use JSON; 

my %test_hash = (
    "fish"   => "paste",
    "apples" => "pears"
);
my $json_text = encode_json ( \%test_hash );
print "Encoded: ",$json_text,"\n";

system( "perl", "some_other_script.pl", quotemeta $json_text );

通话中:

#!/usr/bin/env perl
use strict;
use warnings;
use JSON;
use Data::Dumper;

my ($imported_scalar) = @ARGV; 
$imported_scalar =~ s,\,,g;
print "Got: ",$imported_scalar,"\n";

my $thing =  decode_json $imported_scalar ;

print Dumper $thing;

不幸的是,需要引用元和删除斜杠,因为 shell 对它们进行了插值。如果您尝试执行此类操作,这是常见问题。