JPERL: Accessing Perl from Java
by S. Balamurugan


Listing One
// Passing String array as argument to Perl. 
// Intger and Double arrays can be passed similarly.
String[]  INP = new String[2];

// ... fill in INP

perl.PLCallScalar("MyFunc",INP); // Ditto for PLCallArray & PLCallHash

Listing Two
// Passing a Hashtable and Vector as arguments to Perl 
Object[] ARGS = new Object[2];
Vector    V;
Hashtable H;

// ... fill in H & V

ARGS[0] = H;
ARGS[1] = V;
perl.PLCallScalar("MyFunc",ARGS); // Ditto for PLCallArray & PLCallHash


Listing Three
test.pl 
sub MyPerlFunc
{
 my($a,$b) = @_;
 print $a,":",$b,"\n";
 return 0;
}
sub TestFuncHash
{
 my($a,$b) = @_;
 my(%ret)  = ("A"=>$a,"B"=>$b);
 return ret;
}

Listing Four
example.java
import java.util.Hashtable;
import java.util.Stack;
import jp; // The Jperl interface
class main
{
 public static void main(String[] args)
  {
   String[] INP = new String[2];
   INP[0] = "Data1";
   INP[1] = "Data2";
   try {
        // The perl file that contains the subroutines
        jp perl = new jp("test.pl"); 

        //Turn on Debug if necessary
        //perl.DebugOn;
        
        // Make a call and ignore the returned value!
        String t = perl.PLCallScalar("MyPerlFunc",INP);

        String[] EvRet = perl.IPLEval("$a = 'This is a test'; 
                                      $b = reverse($a); return ($a,$b);");
       // Display result of evaluation
       for(int i=0;i<EvRet.length;i++)
          {
           System.out.println(EvRet[i]);
          } 
       // Call Hash
       Hashtable H = perl.PLCallHash("TestFuncHash",INP);

       // Output content of Hash
       System.out.println(H.toString());
       }
   catch(IllegalArgumentException e)
     {
      System.out.println("Error caught "+e.getMessage());
     }
   catch(RuntimeException e)
     {
      System.out.println("Error caught "+e.getMessage());
     }
  }
}

Listing Five
// Intialize
PLInit("/user/java/dev/test/mytest.pl");

// Passing a double array to Perl and recieving an int
int I;                            // Return value
double DA[] = { 0.10, 0.20 } ;    // Arguments to the Perl sub
PLCall(I,"TestFuncAI","%F",2,DA); // Length is passed before the array

// Passing an int, float and string to Perl and recieving a Hash array
char **S;
int ct = PLCall(S,"TestFunc","%d%f%s",33,(double)100,"Hello World");
for(int i=0;i<ct;i++)
   {
    printf("%s\n",S[i]);
   }
// Evaluate a Perl expression
ct = PLEval(EvalRet,"$a = 'This is a Test'; @b = split(/\\s+/,$a); 
            return @b;");
// print results here ....
// Free resources
PLCose();


3


