difference between perl's hash and python's dictionary
The most fundamental difference is that perl hashes don't throw errors if you access elements that aren't there.
$ python -c 'd = {}; print("Truthy" if d["a"] else "Falsy")'
Traceback (most recent call last):
File "<string>", line 1, in <module>
KeyError: 'a'
$ perl -we 'use strict; my $d = {}; print $d->{"a"} ? "Truthy\n": "Falsy\n"'
Falsy
$
Perl hashes auto create elements too unlike python
$ python -c 'd = dict(); d["a"]["b"]["c"]=1'
Traceback (most recent call last):
File "<string>", line 1, in <module>
KeyError: 'a'
$ perl -we 'use strict; my $d = {}; $d->{a}{b}{c}=1'
$
If you are converting perl
to python
those are the main things that will catch you out.
Another major difference is that in Python you can have (user-defined) objects as your dictionary keys. Dictionaries will use the objects' __hash__
and __eq__
methods to manage this.
In Perl, you can't use objects as hash keys by default. Keys are stored as strings and objects will be interpolated to strings if you try to use them as keys. (However, it's possible to use objects as keys by using a tied hash with a module such as Tie::RefHash.)