[Tutor] translating some python code to perl

Lloyd Kvam pythontutor at venix.com
Thu Aug 28 19:58:52 EDT 2003


This did not generate any responses, but I thought I'd post my
solution anyway.

#!/usr/bin/perl
# testhash.pl

%d1 = (
     '1' => 'one',
     '2' => 'two',
     'd2' => {'nest1' => 'nest one',
     	'nest2' => 'nest two',}
     );

print "\nlookup 1 in d1: $d1{'1'}\n";
print "\nlookup d2 within d1: $d1{'d2'}\n";
print "\nlookup nest1 in d2 within d1: $d1{'d2'}{'nest1'}\n";
#############
There's probably a better way, but this seems to work.  The initial
variable name is prefixed with a % rather than the usual $ and the
hash is delimited with parentheses.  However, nested hashes do not
require the % and are delimited with curly braces.

My python code (version 2.2) follows:
#!/usr/bin/python
# py2perl.py
'''module to handle some python to perl transformations.
'''
class Py2perl_dict(dict):

	def __init__(self, arg):
	    super(Py2perl_dict, self).__init__(arg)
	    for key,val in self.items():
		if isinstance(val, dict) and not isinstance(val, Py2perl_dict):
		    self[key] = Py2perl_dict(val)

	def __repr__(self):
	    keylist = self.keys()
	    keylist.sort()
	    return ''.join(['{',
                 ','.join(["%s => %s" % (repr(key),repr(self[key])) for key in keylist]),
                 '}'])


if __name__ == '__main__':
	d1 = {'1': 'one',
		'2': 'two',
		'd2': {'nest1': 'nest one',
			'nest2': 'nest two',},
         '3': 'four',
         'd3': {'nest3': 'nest three', 'nest4': 'nest four'},
	}
	perl_d1 = Py2perl_dict(d1)
	print "%%perl_d1 = (%s);" % (repr(perl_d1)[1:-1])
#############(indenting got slightly mangled in pasting to email)#####

The key assumption here is that only dict datatypes must have a different
representation for perl.  So I only provided an alternative dict class
with a perlish __repr__ method.  This should work for my case (unless
the perl guy complains) since the python dictionaries I'm converting
only contain strings and perl seems to accept python's string
representation.

I am certainly open to suggestions for improvements.

Lloyd Kvam wrote:

> I need to provide the contents of a python dictionary to a perl
> programmer as a perl hash table.  
-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582




More information about the Tutor mailing list