Reputation: 544
I am new to perl, at most places where hash is used a reference to python's dictionaries is given. A difference which I have noticed is that the hashes don't preserve the order of elements. I would like to know if there are some more concrete and fundamental differences between the two.
Upvotes: 10
Views: 10032
Reputation: 54117
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.
Upvotes: 20
Reputation: 6798
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.)
Upvotes: 9