Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between perl's hash and python's dictionary

Tags:

python

perl

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.

like image 565
CuriousSid Avatar asked May 20 '12 19:05

CuriousSid


2 Answers

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.

like image 161
Nick Craig-Wood Avatar answered Sep 30 '22 16:09

Nick Craig-Wood


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

like image 35
stevenl Avatar answered Sep 30 '22 16:09

stevenl