boriel.com

Hacks, science and curiosities

Calling Perl functions from Python

– 🕓 1 min read

I'm currently working on a project and need to call old Perl functions from Python (until the perl code is refactorized and translated to python).

A friend of mine told me about PyPerl, but we found it's currently unmaintained. :(

Suppose you have a perl module, named mylib.pl, which has a function like:

sub myfunc
{
    my ($a, $b) = @_;
    ...
    ...

    return result;
}

We wanted to be able to call myfunc function from python, without having to rewrite it.
So I managed to create a python module to wrap perl functions in python, using python decorators. With it, you can call perl functions this way:

from perlfunc import perlfunc, perlreq, perl5lib

@perlfunc
@perlreq('mylib.pl')
def myfunc(a, b):
    pass

This would call the perl function myfunc (defined in library mylib.pl) using a and b as parameters. Lists (and arrays as list of lists) and dictionaries can be passed as parameters (they are conveniently converted to perl).

It seems to work very well. :)
It's licensed GPL, and you can download it from its GitHub repo: perlfunc.py