0

How can I write a Perl hash to file, in such a way that it can be read from Python?

For example:

#!/usr/bin/perl
my %h = (
   foo => 'bar',
   baz => ['a', 'b', 'c'],
   raz => {
       ABC => 123,
       XYZ => [4, 5, 6],
   }
);

dumpHash('/tmp/myhash', %h);

... and

#!/usr/bin/python
h = readHash('/tmp/myhash')
print h

# {
#  'foo': 'bar', 
#  'baz': ['a', 'b', 'c'],      
#  'raz': {
#          'ABC': 123, 
#          'XYZ': [4, 5, 6]
#         }
# }

I normally use Perl's built-in Storable to serialize hashes. I see Python has a Storable reader, but it's not part of the standard distribution.

Is there a way to do this with standard built-ins from both languages.

ikegami
  • 367,544
  • 15
  • 269
  • 518
ajwood
  • 18,227
  • 15
  • 61
  • 104

1 Answers1

0

I missed the 'builtin' requirement on first read of your question, but I digress. JSON is not a built-in in Perl, so you'll have to install via CPAN. Nonetheless, this is probably one of the most efficient and compatible ways to do it.

Perl:

use warnings;
use strict;

use JSON;

my $file = 'data.json';

my %h = (
   foo => 'bar',
   baz => ['a', 'b', 'c'],
   raz => {
       ABC => 123,
       XYZ => [4, 5, 6],
   }
);

my $json = encode_json \%h;

open my $fh, '>', $file or die $!;

print $fh $json;

close $fh or die $!;

Python:

import json

file = 'data.json';
data = json.loads(open(file).read())

print(data)
stevieb
  • 9,065
  • 3
  • 26
  • 36
  • 1
    I was hoping to find a solution with only built-in stuff, but I think you're right that I might as well bite the bullet and grab a CPAN module – ajwood Jul 31 '15 at 18:28
  • Just don't name your Python script `json.py` or it'll conflict with the actual json module. – stevieb Jul 31 '15 at 18:32
  • If you're going to install JSON(.pm), you might as well install JSON::XS and use that instead. – ikegami Jul 31 '15 at 19:53