[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Two dimensional associative arrays in Perl?



> 
> Is it possible to have two dimensional associative arrays in Perl,
> something like:
> 
>  $table{$price, $size} = ("RED", "BLUE");
> 
> where $price and $size can be values like "9.99" and "Large"?
> 

Although the syntax is a little different, you can use a two dimensional
hash.
=====================
#!/usr/local/bin/perl

my %twodim = ( "9.99" => { "Large" => ["RED", "BLUE"],
                           "Small" => ["YELLOW", "BLUE"],
		       },
	       "5.43" => { "Large" => ["YELLOW", "BLUE"],
			   "Small" => ["RED", "BLUE"],
		       },
	   );

my $price = "9.99";
my $size = "Large";

print "@{$twodim{$price}{$size}}\n";
print "$twodim{$price}{$size}[0]\n";
print "$twodim{$price}{$size}[1]\n";
=====================
gives ==>RED BLUE
         RED
         BLUE

As you would hope.

Or closer to what you were asking above 
=====================
#!/usr/local/bin/perl

my $price = "9.99";
my $size = "Large";

$twodim{$price}{$size} = ["RED", "BLUE"];

print "@{$twodim{$price}{$size}}\n";
print "$twodim{$price}{$size}[0]\n";
print "$twodim{$price}{$size}[1]\n";
=====================
give the same.

OR 
=====================
#!/usr/local/bin/perl

my $price = "9.99";
my $size = "Large";
@value = ("RED", "BLUE");

$twodim{$price}{$size} = \@value;

print "@{$twodim{$price}{$size}}\n";
print "$twodim{$price}{$size}[0]\n";
print "$twodim{$price}{$size}[1]\n";
=====================
Does the same.

- Dan Griffin
  dang@cs.brandeis.edu

PS, Campmor ay? Any good sales coming up?

> 
> ------------------------------------------------------------------------
> Dan Shoop                                   Campmor, Inc.
> Internet Architect                          28 Parkway
> shoop@campmor.com                           Upper Saddle River, NJ 07458
> (201) 825-8300 x3035                        http://www.campmor.com/
>