Search code examples
perl

foreach printing array elements


I'm trying to loop through multiple array elements, and based on the array, I'm trying print each element with its corresponding value.

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

Here is what I have tried. I'm not sure how to use conditions to get the desired output:

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

Desired output

 {
        "data":[

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

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

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

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

        }

        ]
}

Solution

  • If both arrays are always the same size, it would be simpler to loop through the indexes of the array than the actual elements.

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

    Also there is no need to build up a JSON string like this in Perl, there is a nice module on CPAN called JSON which can create them for your from a hash.

    So, knowing this you can simply create a hash:

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