Accessing Array Elements of Data Structure

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • eWish
    Recognized Expert Contributor
    • Jul 2007
    • 973

    Accessing Array Elements of Data Structure

    Let's say you have the following data structure.

    [CODE=perl]$VAR1 = {
    'xxx' => {
    'xxx' => {
    'xxx' => [
    'xxx',
    'xxx',
    'xxx',
    'xxx',
    'xxx'
    ]
    }
    }
    };[/CODE]
    Say you want to access the array portion, is there a more elegant way of accessing the array data?

    [CODE=perl]$product_data{$ category}->{$sub_category }->{$product_name }[0];[/CODE]
    --Kevin
  • KevinADC
    Recognized Expert Specialist
    • Jan 2007
    • 4092

    #2
    If that is all the data you have, that is the only way to access it initially. If $var is not a reference itself you can dispense with the arrow operator:
    Code:
    %hash = (
       xxx => {
          xxx => {
             xxx => [qw(xxx xxx xxx)]
          }
       }
    );
    
    print $hash{xxx}{xxx}{xxx}[0]
    But you could have the last hash key point to an array:

    Code:
    use Data::Dumper;
    my @yellow_pencils = qw(foo bar baz);
    
    my %product_data = (
       'pencils' => {
    	   '#2' => {
             'yellow' => \@yellow_pencils
          }
       }
    );
    
    print Dumper \%product_data;
    Now if all you needed was the data in the array you could access the array and only use the hash when necessary. That is one thing about references, you can make your data almost as arbitrarily complicated as you want. How practical/impractical this approach is though is probably open to debate.

    Comment

    • eWish
      Recognized Expert Contributor
      • Jul 2007
      • 973

      #3
      That is what I thought. I was just wondering if there was away I was not familiar with. As always thanks for your input!

      --Kevin

      Comment

      Working...