Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a Perl function in Python

Tags:

python

perl

I have a few functions written in a Perl module. I have to call these functions in Python and get the output.

I have seen the link http://en.wikibooks.org/wiki/Python_Programming/Extending_with_Perl. I am not able to find the Perl module which they have imported in Python.

When I try to install pyperl in Linux, it is not able to find it.

I am able to run simple Perl script and get the output, but I am unable to call a function written in Perl and get the output.

like image 720
Jack Avatar asked Jan 19 '14 07:01

Jack


People also ask

Can Python use a Perl module?

It is possible to call Perl functions and modules in Python. One way to do that is the PyPerl Module.

Can we convert Perl script to Python?

Here are the simple steps to convert PERL scripts to Python. Remove all ';' at the end of the line. Remove all curly brackets and adjust indentation. Convert variables names from $x, %x or @x to x.


1 Answers

Use popen to run the Perl interpreter and execute the desired code. When running Perl, include the -m MODULE switch to load the desired module(s) and -e EXPRESSION to execute the function you want. For example, this code runs a function in the POSIX module and obtains its (string) result:

>>> os.popen('''
... perl -mPOSIX -e "print POSIX::asctime(localtime)"
... ''').read()
'Sun Jan 19 12:14:50 2014\n'

If you need to transmit more involved data structures between Python and Perl, use an intermediate format well supported in both languages, such as JSON:

>>> import os, json
>>> json.load(os.popen('''
... perl -e '
...   use POSIX qw(localtime asctime);
...   use JSON qw(to_json);
...   my @localtime = localtime(time);
...   print to_json({localtime => \@localtime,
...                  asctime => asctime(@localtime)});
... '
... '''))
{u'localtime': [10, 32, 12, 19, 0, 114, 0, 18, 0],
 u'asctime': u'Sun Jan 19 12:32:10 2014\n'}
like image 171
user4815162342 Avatar answered Oct 04 '22 04:10

user4815162342