[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"?

Not with that syntax.  Two ways to do this.  Here's the perl4 way, using 
a string "RED BLUE" instead of an array:


# PERL 4 WAY

sub put_table {
my($a, $b, $value) = @_;
$table{"$a\001$b"} = $value;
}

sub get_table {
my($a, $b) = @_;
return $table{"$a\001$b"};
}

&put_table($price, $size, "RED BLUE");
print &get_table($price, $size);


This is considered inferior to the perl5 way.  Here's what it looks like, 
first using a string "RED BLUE" and then an anonymous array with the two 
items "BLUE" and "RED":


# PERL 5 WAY

$table = { }; # create a reference to an anonymous hash
              # (this step not strictly necessary)

$price = 9.99; $size = "large";
$table->{$price}{$size} = "RED BLUE"; # this entry is a string

$price = 99.99; $size = "extralarge";
$table->{$price}{$size} = ["BLUE", "RED"]; # this entry is a ref.
                                           # to an anon. list

print "$table->{9.99}{large}\n";      # prints "RED BLUE\n"

print join(':',                       # prints "BLUE:RED\n"
      @{$table->{99.99}{extralarge}}
   ) . "\n";



The syntax is simple once you get familiar with seeing it, but there's a 
fair amount going on behind the scenes to make that $a->{b}{c}{d} stuff 
possible.  One important fact is that referencing $a->{b}{c}{d} as an 
lvalue not only causes item {d} in the hash $a->{b}{c} to come into 
existence, but also does the same for item {b} in $a and item {c} in 
$a->{b}.

If all this is Greek to you, you haven't read chapter 4 of the 2nd ed. 
Camel :-)


--
 Jamie McCarthy          http://www.absence.prismatix.com/jamie/
 jamie@voyager.net        Co-Webmaster of http://www.nizkor.org/