我的程序登录到IP列表,识别其上运行的软件,并打印输出。
我希望输出采用JSON数组的形式。
可以使用JSON编码功能吗?
use strict;
use warnings;
use QA::unit::testbedinfo;
my @machines_under_test = ( ... ); # list of ip's listed here
sub test_1_get_install_info_of_machines_under_test {
my ( $self ) = @_;
my %output;
foreach my $ip ( @machines_under_test ) {
my $output = $self->{'queryObj'}->get_install_info( $ip );
push @{ $output{$output} }, $ip;
INFO( ' software version running on machine ' . $ip . ' : ' . $output );
}
return 1;
}
答案 0 :(得分:1)
所以看起来你正在构建一个哈希%output
,它具有键的软件版本号和(引用)值的IP地址数组,对吗?要将该结构输出为JSON,只需使用JSON模块并打印to_json
函数的输出:
#!/usr/bin/env perl
use warnings;
use strict;
use 5.010;
use JSON 'to_json';
my %output = (
'1.0' => [ qw( 1.2.3.4 5.6.7.8 ) ],
'1.1' => [ qw( 192.168.0.3 192.168.37.42 192.168.0.123 ) ]
);
# Note that to_json takes a reference to the structure, not the raw hash
say to_json(\%output);
产生输出:
{"1.0":["1.2.3.4","5.6.7.8"],"1.1":["192.168.0.3","192.168.37.42","192.168.0.123"]}