perl 每个打印阵列元素

jutyujz0  于 2023-06-06  发布在  Perl
关注(0)|答案(2)|浏览(245)

我尝试循环遍历多个数组元素,并基于数组,尝试打印每个元素与其对应的值。

@_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"

        }

        ]
}
pgx2nnw8

pgx2nnw81#

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

# 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"}]}
k4emjkb1

k4emjkb12#

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

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";
}

相关问题