[Israel.pm] Python talk
Uri Bruck
bruck at actcom.net.il
Tue Dec 7 00:48:29 PST 2004
Mikhael Goikhman wrote:
> 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.
perl allows hash keys such as
$COMPLICATED_ASSOC_ARRAY{0,90}
$COMPLICATED_ASSOC_ARRAY{'foo',1}
etc.
The documentation for the module Offer found even compares this to what
the module offers.
> 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.
>
--
Thanks,
Uri
http://translation.israel.net
More information about the Perl
mailing list