[Israel.pm] Python talk

Mikhael Goikhman migo at homemail.com
Mon Dec 6 23:23:39 PST 2004


On 07 Dec 2004 05:46:27 +0200, Omer Zak wrote:
> 
> I'll write, in Python, an associative array, whose keys are arrays and
> its data are themselves associative arrays.  Show me how to write it in
> Perl.

Are you sure the keys of your COMPLICATED_ASSOC_ARRAY may be associative
arrays by themselves? Python gives me an arror when I try to do this.
It seems that the keys of the Python "hash" can be "arrays", but not
"hashes". So, your statement above is not true.

> COMPLICATED_ASSOC_ARRAY = {
>   (0,0) : { "label" : "Origin of the World", "population" : 0 },
>   (0,90): { "label" : "North Pole", "population" : "varies, usually 0"},
>   (0,-90):{ "label" : "South Pole", "population" : ("penguins",10E6)}
> }

Ok, Perl only allows strings or numbers to be the hash keys. But to
simulate keys that are arrays, you may map array to string. So here is
the Perl code:

$COMPLICATED_ASSOC_ARRAY = {
  '0,0'   => { label => 'Origin of the World', population => 0 },
  '0,90'  => { label => 'North Pole", population => 'varies, usually 0' },
  '0,-90' => { label => 'South Pole", population => [ penguins => 10E6 ] },
}

To get the array back from the key (if you ever need this), you may split
the key by the separator, or better store the array in the hash too, ie.:

  { label => 'somewhere', population => 12, time => [ 10, 20 ] }

And if the keys are constant arrays and not variable arrays, then you
don't even need to join the array elements to construct the key (but you
should be aware that Perl converts arrayref to string here):

  $time = [ 100, 200 ];
  $CAA->{$time} = { label => 'somewhere', population => 12, time => $time };

I used both methods (string as keys and arrayrefs as keys) to solve such
tasks, and it works well, it even works with hashrefs as keys, something
that Python does not support. All in all, I don't think that working with
arrays as the keys is more intuitive than working with strings as the
keys. And I don't see anything real-life fundamental that Perl misses.

Does someone know whether Perl 6 will allow any object to be hash key?

Regards,
Mikhael.

-- 
perl -e 'print+chr(64+hex)for+split//,d9b815c07f9b8d1e'



More information about the Perl mailing list