How can I call Perl from Java?

前端 未结 9 1701
自闭症患者
自闭症患者 2020-12-04 22:42

I have a Perl module that I would like to use from Java. Is there a way to call this code using either ActiveState Perl on Windows or the generic Perl that comes with Linux?

相关标签:
9条回答
  • 2020-12-04 23:20

    Inline-Java is the usual library to call java from Perl, and this post propose a org.perl.java module which should allow calling Perl from Java, as asked.

    However, because of the unpredictability of the JNI implementations for different JVMs it is difficult to say what combinations of JVM and Perl will work. Typically, what is required is Perl with MULTIPLICITY, and threads compiled in. That means he uses a custom built Perl.

    Otherwise, Inline::Java::Callback allows you to call Perl functions from Java. To do this you need to create an org.perl.inline.java.InlinePerlCaller object. Here is a example of a typical use:

    use Inline Java => <<END ;
    import java.util.* ;
    import org.perl.inline.java.* ;
    
    class Pod_regexp extends InlineJavaPerlCaller {
        public Pod_regexp() throws InlineJavaException {
        }
    
        public boolean match(String target, String pattern)
            throws InlineJavaException {
            try {
                String m = (String)CallPerlSub("main::regexp",
                new Object [] {target, pattern}) ;
    
                if (m.equals("1")){
                return true ;
            }
        }
        catch (InlineJavaPerlException pe){
            // $@ is in pe.GetObject()
        }
    
        return false ;
        }
    }
    END
    
    my $re = new Pod_regexp() ;
    my $match = $re->match("Inline::Java", "^Inline") ;
    print($match . "n") ; # prints 1
    
    sub regexp {
        my $target = shift ;
        my $pattern = shift ;
    
        return ($target =~ /$pattern/) ;
    } 
    
    0 讨论(0)
  • 2020-12-04 23:21

    Guess it really depends on what your perl code is, and what you're trying to do..

    If just using exec() is too simple, something like gearman could be helpful

    0 讨论(0)
  • 2020-12-04 23:27

    I've used Inline::Java a bit, and found it a bit fiddly, if I had my time over, I'd probably reimplement using web services and call the perl code that way.

    0 讨论(0)
  • 2020-12-04 23:29

    Is this not what Runtime.exec() is for?

    Runtime.getRuntime().exec("/usr/bin/perl myPerl.pl");
    

    Or am I misunderstanding the question?

    0 讨论(0)
  • 2020-12-04 23:30

    Rakudo allows you to run Perl6 inside a JVM, and there is a Perl5 add-on that allows you to run most old code, although no XS of course. There is also JERL that runs current microperl inside the JVM. It depends a lot on what you're looking to do, but those are worth checking out.

    0 讨论(0)
  • 2020-12-04 23:33

    I know this is old, but I recently came across the same needs. I found JPerl more convenient then Inline::Java::PerlInterpreter.

    0 讨论(0)
提交回复
热议问题