Search code examples
perl

I am trying to pass this array but with numbers only into function


I am writing a small automation script for a workflow for my job. I need to pass a set of numbers as inputs (which are beginning input from a JSON file) into my Perl function. Here is my code:

my $idFile='GNOC_IDS.json';
my $idJSON;
{
    local $/;
    open my $fh, '<', $idFile or die $!;
    $idJSON = <$fh>;
    close $fh;
}
my $id_array = decode_json $idJSON;
my @decodedIDS = Dumper(\$id_array);
foreach my $ids(@decodedIDS){
    print $ids;
    my $results= $client->get_entities(
            entity_id=>$ids

            );
    print Dumper(\$results);
}

However, my problem is that the $ids have the following format:

[       {
          'MISC' => '1743'
        },
        {
          'MISC' => '1743'
        },
        {
          'MISC' => '1733'
        },
        {
          'MISC' => '2736'
        },
        {
          'MISC' => '1763'
        },
        {
          'MISC' => '3133'
        },
        {
          'MISC' => '1743'
        },
        {
          'MISC' => '1733'
        },
        {
          'MISC' => '2802'
        },
        {
          'MISC' => '1699'
        },
        {
          'MISC' => '2736'
        },
        {
          'MISC' => '2600'
        }
]

I want to feed just the numbers (e.g., 1699, 2735, etc.) into the get_entities function because right now its giving me an "input must be integer only error".


Solution

  • Assuming your $id_array is as follows, you can use map instead of Dumper to access just the numbers:

    use warnings;
    use strict;
    use Data::Dumper;
    
    my $id_array = [
            {
              'MISC' => '1743'
            },
            {
              'MISC' => '1743'
            },
            {
              'MISC' => '1733'
            },
            {
              'MISC' => '2736'
            },
            {
              'MISC' => '1763'
            },
            {
              'MISC' => '3133'
            },
    ];
    
    my @decodedIDS = map { $_->{MISC} } @{ $id_array };
    print Dumper(\@decodedIDS);
    

    Output:

    $VAR1 = [
              '1743',
              '1743',
              '1733',
              '2736',
              '1763',
              '3133'
            ];