Search code examples
pythonperlcross-language

Writing a Perl hash to disk to be read by Python


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.


Solution

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