Monday, March 16, 2009

Thar' be Perl!

This weekend was the start of Spring Break for University of Maryland students, and like all good students I spent my time doing worthwhile things; namely sleeping, eating, and my personal favorite: learning Perl.

For those of you who don't know, Perl is quite a nifty scripting language with some incredibly powerful features. I won't go into said features at the moment, mostly because I really don't quite understand them myself. What I do understand however, is how to interface Java and Perl, which is quite an interesting and awesome feature, if I say so myself.

(Please note: I'm perfectly aware I'm far from the first to discover this, but it took me some time to figure out how to get Perl set up so that it worked properly on windows for Java/Perl interpretation, so let me have my fun in posting this!)

First of all, I downloaded ActiveState Perl, which also installed the Perl Package Manager. The first thing you want to do is boot up the Manager, open the packages you have no yet installed, and install Inline.

First, make sure that you have the most recent version of the Java 2.0 SDK installed on your computer. You can get it here.

Then you want to follow this link which will download the archive for Inline::Java. Once you have downloaded it, extract it fully. Then go here, and download a "make" for windows. Run the .exe and then move the nmake.exe file to your Perl bin. This should allow you to make packages for the perl interpreter now.

Now open up cmd.exe and navigate to the folder where you have extracted the Inline::Java. Once there, run these commands:

>>perl Makefile.PL J2SDK=/java/directory/
>>nmake
>>nmake test
>>nmake install


And there you go! You can now compile Java code (Not interpret, compile. It saves the Inlined compilation and does not run through it again unless it has been changed.)

A simple example of using Java in a perl script is below:

'JavaTest.pl'

use Inline Java => <<'END';
class Tester{
public Tester(){}
public void Printout(){System.out.println("Hello!");}
}
END

$test=new Tester();
$test->Printout();


The output for this code is: Hello!

You can do practically anything with this, including calling Perl subroutines inside the Java code. This is called Callback, and is used by importing org.perl.inline.java.* and using several of the functions within it. I may have more of that one this site at some point, but there is a wealth of information, (I've already found a couple sites) on the internet. Go look them up!

-J