foreach打印数组元素

时间:2014-04-16 14:29:31

标签: perl scripting

我试图遍历多个数组元素,并且基于数组,我尝试使用相应的值打印每个元素。

@_disk = ('0:0','0:1');
@_diskStatus= ('OK','Critical');

以下是我的尝试,我不确定如何使用条件来获得所需的输出:

foreach (@_diskID, @_diskStatus)
{
    # Print the data in JSON
    print "\t,\n" if not $_first;
    $_first = 0;

    print "\t{\n";
    print "\t\t\"{#DISKID}\":\"$_\"\n";
    print "\n\t}\n";
}

print "\n\t]\n";
print "}\n";

期望的输出

 {
        "data":[

        {
            "{#DISKID}":" 0:0"

        }
        ,
        {
            "{#STATUS}":" Ok"

        }
        ,
        {
            "{#DISKID}":" 0:1"

        }
        ,
        {
            "{#STATUS}":" Critical"

        }

        ]
}

2 个答案:

答案 0 :(得分:3)

如果两个数组的大小始终相同,则循环数组的索引比实际元素更简单。

# only need one array here because they are the same size
foreach my $i ( 0 .. $#_diskID ) { 
   ...
}

此外,没有必要在Perl中建立这样的JSON字符串,CPAN上有一个名为JSON的好模块,它可以从哈希创建它们。

所以,知道这一点你就可以简单地创建一个哈希:

use strict;
use warnings;

use JSON;

my @_disk = ('0:0','0:1');
my @_diskStatus= ('OK','Critical');

my %json_hash = ( data => [] );
foreach my $i ( 0 .. $#_disk ) {
   push @{$json_hash{data}},
      { '{#DISKID}' => $_disk[$i],
        '{#STATUS}' => $_diskStatus[$i],
      };
}

my $json_string = encode_json \%json_hash;
print "$json_string\n";

# prints
# {"data":[{"{#STATUS}":"OK","{#DISKID}":"0:0"},{"{#DISKID}":"0:1","{#STATUS}":"Critical"}]}

答案 1 :(得分:1)

假设两个数组具有相同数量的元素:

use warnings;
use strict;

my @_disk = ('0:0','0:1');
my @_diskStatus = ('OK','Critical');

for my $i (0 .. $#_disk) {
    print "$_disk[$i] $_diskStatus[$i]\n";
}