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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Hash "pointing to" an array?

Status
Not open for further replies.

CJason

Programmer
Oct 13, 2004
223
US
Me again!?!?

Question:
I need to associate hash elements to arrays. That is (something like this):

$hash{THIS} -> @array1;
$hash{THAT} -> @array2;

Does that make any sense? Basically, I need to look to see if a hash key exists, if it does, then loop thru the corresponding array.

How would I set something like this up? Or, can someone think of a better way of doing this?
 
Code:
if (exists $hash{THIS}) {
   foreach my $this (@array1) {
       print "$this\n";
   }
}

Wether that is the best way to go about it depends on what you are doing.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Kevin, how do I associate the $hash{THIS} with @array1? Maybe this will describe it more...in this "code" below:

Code:
if (exists($hash($checkthis))) {
  foreach $this ($hash{$checkthis}->@array) {
    print "$this\n";
  }
}
 
Perl:
push @{$hash{$checkthis}}, 'stuff'; # automatically create array

$hash{$checkthis} = []; # set it to an empty anonymous array

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
Steve, that looks like what I'm looking for. Let me add another twist to it...how do I make that array, 2-dimensional?

Code:
push @{$hash{$checkthis},1}, 'stuff'; # automatically create array

????
 
I think I got what I'm looking for...does this seem correct:

Code:
$array[0][0] = 'stuff';
$hash{THIS} = [@array]; 
print "$hash{THIS}[0][0]\n";
 
See the first three tutorials on this page:


perlreftut - Mark's very short tutorial about references
perldsc - data structure complex data structure struct
perllol - Manipulating Arrays of Arrays in Perl

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
I think I found the datastructure I'm looking for. HoAoA (Hash of Arrays of Arrays)!! Putting all the above examples and tutorials together, I think I've figured it out!

Thanks guys...you again saved my arse!
 
Good. I always find Data::Dumper to be a big help on these occasions
Perl:
use Data::Dumper;
print Dumper(%myReallyComplicatedStructure);

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top