我有JSON格式的这种数据
{
"stream 8": {
"stream_name": "xyz",
"field1": "xe-0/0/1",
"field2": "at-0/0/0"
},
"stream 12": {
"stream_name": "abc",
"field1": "br-0/1/1",
"field2": "at-1/0/1"
}
}
我将这个JSON对象发送到Perl CGI脚本,然后将其转换为哈希哈希值。
现在我想使用命令行参数将此哈希引用发送到另一个Perl脚本。我不知道它为什么不起作用。
这是我的CGI脚本
#!c:/perl/bin/perl.exe
use CGI;
use strict;
use warnings;
use JSON;
use JSON::PP;
use Data::Dumper;
use Storable;
# read the CGI params
my $q = CGI->new;
my $json = $q->param("r");
print "Content-type:text/html\n\n";
my $href = decode_json($json);
my %arr = %{$href};
my %hash;
foreach my $key (keys %arr) {
my %a = %{$arr{$key}};
foreach my $value (keys %a) {
$hash{$key}{'streamname'} = $a{'stream_name'};
$hash{$key}{'f1'} = $a{'field1'};
$hash{$key}{'f2'} = $a{'field2'};
}
}
my @h = %hash;
#print ref(@h);
print Dumper(@h);
my $out;
$out = `perl te.pl @h hashval`;
Te.pl
use strict;
use warnings;
use Data::Dumper;
use Storable;
print("\nIn sample\n");
if ( $ARGV[-1] eq 'hashval' ) {
#print("\nIts hash\n");
delete($ARGV[-1]);
my %h1 = @ARGV;
print Dumper(%h1);
}
当我打印%h1
时,我无法获得所需的输出。
请告诉我如何解决这个问题,因为我是Perl和CGI的新手。
答案 0 :(得分:2)
您应该将数据作为JSON发送。 IPC::Open3可能是个不错的选择:
$pid = open3(\*CHLD_IN, \*CHLD_OUT, \*CHLD_ERR,
'perl te.pl');
print CHLD_IN $r;
close CHLD_IN;
您仍然可以从CHLD_OUT
读取结果,而不是使用反引号。
在te.pl中:
{
local $/ = undef;
my $json = <STDIN>;
}
使用{ ... }
块将$/
的修改限制为该操作。
...但为什么需要调用外部脚本?为什么不通过require
或moving the required functions to a module加载?
答案 1 :(得分:1)
您的哈希是嵌套的。通过打印它,您只需获取reftype和地址,因此您将调用此命令:
perl te.pl key HASH(0x2886cd0)
哪个失败,因为括号对于shell来说是特殊的。
我宁愿将JSON发送到脚本,也许是通过文件或管道。