shilpam has asked for the wisdom of the Perl Monks concerning the following question:

I want to construct an array like
$a = "fruits"; $b = "birds"; $c = "p"; $d = "g"; $e = "c"; @array1[$a][$c]="peach"; @array1[$a][$d]="grapes"; @array1[$b][$c]="parrot"; @array1[$b][$e]="crow";
How can I construct this kind of array? Also how do I access the data easily?
Or should I use some other data type?

20040728 Edit by ysth: remove <BR>'s from within code tags

Replies are listed 'Best First'.
Re: multi dimension array
by davido (Cardinal) on Jul 28, 2004 at 06:11 UTC

    You are talking about a hash (otherwise known as an associative array). Here's an example of the Perlish way to construct an associative array similar to what you're depicting.

    use Data::Dumper; my %world = ( 'fruits' => { 'p' => 'peach', 'g' => 'grapes', } 'birds' => { 'p' => 'parrot', 'c' => 'crow' } ); print Dumper \%world; print "Accessing individual elements:\n"; print $world{'fruits'}{'p'}, "\n"; print $world{'birds'}{'c'}, "\n";

    Please refer to perldata and perlintro for starters, to learn about hashes. For multidimensional structures you'll need to read perlreftut, perllol, and perlref. Enjoy! It's good stuff.


    Dave

Re: multi dimension array
by ccn (Vicar) on Jul 28, 2004 at 06:13 UTC

    You should use HoH (a Hash of Hashes)

    my %HoH; $a = "fruits"; $b = "birds"; $c = "p"; $d = "g"; $e = "c"; $HoH{$a}{$c}="peach"; $HoH{$a}{$d}="grapes"; $HoH{$b}{$c}="parrot"; $HoH{$b}{$e}="crow"; foreach my $k (keys %HoH) { foreach my $j (keys %{$HoH{$k}}) { print "\$HoH{$k}{$j} = $HoH{$k}{$j}\n"; } }

    see perlreftut