skip to Main Content

Got some problems to access json values (translated from xml).

for my $PORT (0..$#PORTS)
{
    print Dumper $PORTS[$PORT]->{'neighbor'};
    if (defined($PORTS[$PORT]->{'neighbor'}->{'wwn'}->{'$t'}))
    {
        print Dumper @{$PORTS[$PORT]->{'neighbor'}->{'wwn'}->{$t}};
    }
    else
    {
        print Dumper "not defined"
    }
}

Test works when $PORTS[$PORT]->{'neighbor'} is empty but I’ve an error when it contains some value.

$VAR1 = {};
$VAR1 = 'not defined';
$VAR1 = {};
$VAR1 = 'not defined';
$VAR1 = {
          'wwn' => [
                     {
                       '$t' => 'xxx'
                     },
                     {
                       '$t' => 'yyy'
                     },
                     {
                       '$t' => 'zzz'
                     }
                   ]
        };
Not a HASH reference at ./xxxxx.pl line 209.

Line 209 is the line of the test :

if (defined($PORTS[$PORT]->{'neighbor'}->{'wwn'}->{'$t'}))

Don’t know what I miss !
Some clues ?

2

Answers


  1. Chosen as BEST ANSWER

    Finally solved by checking type returned :

    for my $port ( @PORTS )
    {
        my $neighbor = $port->{ neighbor };
        if ( my $wwn = $neighbor->{ wwn } )
        {
            if (ref($wwn) eq "ARRAY")
            {
                for ( @$wwn )
                {
                    my $val = $_->{'$t'};
                    print Dumper "array-val : ".$val; 
                }
            }
            else
            {
                print Dumper "hash-val : ".$wwn->{'$t'};
            }
        }
        else
        {
            print Dumper "pas de wwn pour ce port";
        }
    }
    

    Thanks to all...


  2. Two errors.

    In the undefined case, you check if $PORTS[$PORT]{neighbor}{wwn}{'$t'} is defined as if $PORTS[$PORT]{neighbor}{wwn} is a reference to a hash, but it’s $PORTS[$PORT]{neighbor}{wwn} that’s not defined.

    In the defined case, you use $PORTS[$PORT]{neighbor}{wwn} as a reference to a hash when it’s actually a reference to an array.

    for my $port ( @PORTS ) {
       my $neighbor = $port->{ neighbor };
       if ( my $wwn = $neighbor->{ wwn } ) {
          for ( @$wwn ) {
             my $val = $_->{'$t'};
             ...
          }
       } else {
          ...
       }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search