By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,242 Members | 1,369 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,242 IT Pros & Developers. It's quick & easy.

Accessing Array Elements of Data Structure

eWish
Expert 100+
P: 971
Let's say you have the following data structure.

Expand|Select|Wrap|Line Numbers
  1. $VAR1 = {
  2.           'xxx' => {
  3.                      'xxx' => {
  4.                                 'xxx' => [
  5.                                            'xxx',
  6.                                            'xxx',
  7.                                            'xxx',
  8.                                            'xxx',
  9.                                            'xxx'
  10.                                            ]
  11.                               }
  12.                    }
  13.         };
Say you want to access the array portion, is there a more elegant way of accessing the array data?

Expand|Select|Wrap|Line Numbers
  1. $product_data{$category}->{$sub_category}->{$product_name}[0];
--Kevin
Apr 12 '08 #1
Share this Question
Share on Google+
2 Replies


KevinADC
Expert 2.5K+
P: 4,059
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:
Expand|Select|Wrap|Line Numbers
  1. %hash = (
  2.    xxx => {
  3.       xxx => {
  4.          xxx => [qw(xxx xxx xxx)]
  5.       }
  6.    }
  7. );
  8.  
  9. print $hash{xxx}{xxx}{xxx}[0]
But you could have the last hash key point to an array:

Expand|Select|Wrap|Line Numbers
  1. use Data::Dumper;
  2. my @yellow_pencils = qw(foo bar baz);
  3.  
  4. my %product_data = (
  5.    'pencils' => {
  6.        '#2' => {
  7.          'yellow' => \@yellow_pencils
  8.       }
  9.    }
  10. );
  11.  
  12. print Dumper \%product_data;
  13.  
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.
Apr 13 '08 #2

eWish
Expert 100+
P: 971
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
Apr 13 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.