difference between perl's hash and python's dictionary

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.


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"'

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.)

Need Your Help

Waiting on a list of Future

java multithreading future

I have a method which returns a List of futures

Android View Disappearing When Go Outside Of Parent

java android animation android-animation

I have a LinearLayout and ImageView inside this LinearLayout.