Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

array in a hash in a hash access 2

Status
Not open for further replies.

arcnon

Programmer
Aug 12, 2003
242
US
    1. Is this the correct way to write this data structure? Suggestions?
    2. How do I access the size of the 'disallowed' array?
    3. What is the best way to foreach this array?

my %t_type = (
'a' => {
'chance' => {'low' => 2, 'high' => 12, 'percent' => 50},
'range' => {'number' => '','disallowed' => ['none','1','2']},
}
);

print "$t_type{'a'}{'magic'}{'disallowed'}[2] \n";

I am not having problems accessing the array slice but getting the entire array info is proving troublesome.
thanks in advanced
 
1. Yes, it's correct (though quoting hash keys is optional).
2. You can get the size of the array by using the name of the array (witn @) in a scalar context, as usual.
3. The code below loops through %t_type, extracts each array into temporary variable @arr (note the @{...} dereference), and then loops through the array. I used a C-style for since it demonstrates getting the size of the array; but you could certainly use a for my $a (@arr) here.
Code:
#!perl
use strict;
use warnings;

my %t_type = (
    a => {
        chance => {low => 2, high => 12, percent => 50},
        range => {number => '', disallowed => ['none', 1, 2]},
    }
);

for my $key (sort keys %t_type) {
    my @arr = @{$t_type{$key}{range}{disallowed}};
    for (my $i=0; $i<@arr; $i++) {
        print "$arr[$i]\n";
    }
}
[b]Output[/b]
none
1
2
HTH
 
thanks for the leads guys I ended up changing my structure abit but posts proved quite useful.

additional thanks mike once again. you have sent me down the correct path to a solution.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top