Accessing data in references?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mangoo
    New Member
    • Mar 2008
    • 1

    Accessing data in references?

    Let's say we have the following code:
    [code=perl]
    my $VAR1 = {
    'target' => {
    'oranges' => {
    'size' => 'big'
    },
    'apples' => {
    'size' => 'small'
    }
    }
    }

    print $VAR1;
    [/code]


    Now, to get the size of apples, we would use:
    [code=perl]
    print $VAR1->{'target'}->{'oranges'}->{'size'};
    [/code]

    But to do this, I have to know that there are oranges stored there, and that their size is defined.

    How can I iterate all elements that are stored? I would like to display:

    oranges, size: big
    apples, colour: red
    Last edited by numberwhun; Mar 11 '08, 03:01 PM. Reason: add code tags
  • KevinADC
    Recognized Expert Specialist
    • Jan 2007
    • 4092

    #2
    Originally posted by mangoo
    Let's say we have the following code:
    [code=perl]
    my $VAR1 = {
    'target' => {
    'oranges' => {
    'size' => 'big'
    },
    'apples' => {
    'size' => 'small'
    }
    }
    }

    print $VAR1;
    [/code]


    Now, to get the size of apples, we would use:
    [code=perl]
    print $VAR1->{'target'}->{'oranges'}->{'size'};
    [/code]

    But to do this, I have to know that there are oranges stored there, and that their size is defined.

    How can I iterate all elements that are stored? I would like to display:

    oranges, size: big
    apples, colour: red
    loops and references:

    [code=perl]
    my $VAR1 = {
    'target' => {
    'oranges' => {
    'size' => 'big'
    },
    'apples' => {
    'size' => 'small'
    }
    }
    };

    foreach my $keys (keys %{$VAR1}) {
    foreach my $sub_keys (keys %{$VAR1->{$keys}}) {
    print "$sub_keys, ";
    foreach my $sub_sub_keys (keys %{$VAR1->{$keys}->{$sub_keys}} ) {
    print "$sub_sub_k eys: $VAR1->{$keys}->{$sub_keys}->{$sub_sub_keys }\n";
    }
    }
    }
    [/code]

    See the reply on devshed where a member there took a lot of time and effort to reply to your question.

    Comment

    • numberwhun
      Recognized Expert Moderator Specialist
      • May 2007
      • 3467

      #3
      If I may add, take a look at this web site as it may help with issues like this in the future.

      Regards,

      Jeff

      Comment

      Working...