Search code examples
perldata-structuresiteratorcomplex-data-types

Iterating over data structure


I am trying to iterate over this data structure:

$deconstructed->{data}->{workspaces}[0]->{workspace}->{facts}[0]->{code}

where fact[0] is increasing. It's several files I am processing so the number of {facts}[x] varies.

I thought this might work but it doesn't seem to be stepping up the $iter var:

foreach $iter(@{$deconstructed->{data}->{workspaces}[0]->{workspace}->{facts}}){
  print $deconstructed->{data}->{workspaces}[0]->{workspace}->{facts}[$iter]->{code}."\n";
}

I'm totally digging data structures but this one is stumping me. Any advice what might be wrong here?


Solution

  • $iter is being set to the content of each item in the array not the index. e.g.

    my $a = [ 'a', 'b', 'c' ];
    for my $i (@$a) {
        print "$i\n";
    }
    

    ...prints:

    a
    b
    c
    

    Try:

    foreach $iter (@{$deconstructed->{data}->{workspaces}[0]->{workspace}->{facts}}){
        print $iter->{code}."\n";
    }