【问题标题】:Sending a hash of hashes from a Perl CGI program to another Perl script via a command-line argument通过命令行参数将哈希值从 Perl CGI 程序发送到另一个 Perl 脚本
【发布时间】:2016-08-22 22:02:48
【问题描述】:

我有这种 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​​ 的新手,请告诉我如何准确解决此问题。

【问题讨论】:

  • @mkHun:我之前已经要求你不要对别人的帖子进行微不足道的更改。如果您还需要进行重大更改,则将小写字母更正为大写字母是可以的,但单独完成太微不足道了
  • 我不知道你在做什么,但它可能值得将 redis 视为数据结构服务器...@987654321 @ 只是一个想法。
  • @MarkSetchell 我只需将此哈希传递给另一个 perl 脚本,以便作为命令行参数进行进一步处理
  • 为什么需要在命令行传递数据?将 JSON 数据写入临时文件并让 te.pl 读取文件并在内容上调用 decode_json 可能是最简单的,但目前尚不清楚这是否可能
  • %arr@h 是我见过的最令人困惑的两个变量名 :-)

标签: json perl hash cgi


【解决方案1】:

您应该以 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>;
}

使用{ ... } 块将$/ 的修改限制为该操作。

...但是为什么需要调用外部脚本呢?为什么不通过requiremoving the required functions to a module 加载它?

【讨论】:

    【解决方案2】:

    您的哈希是嵌套的。通过打印它,您只需获取 reftype 和地址,因此您正在调用此命令:

    perl te.pl key HASH(0x2886cd0)
    

    因为括号对 shell 是特殊的而失败。

    我宁愿将 JSON 发送到脚本,可能是通过文件或管道。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-14
      • 2012-03-10
      • 2012-10-03
      • 1970-01-01
      • 2012-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多