Java Reference
In-Depth Information
new Object [] {target, pattern});
// Show result
JOptionPane.showMessageDialog(null, "Edit distance between '" + target +
"' and '" + pattern + "' is " + str,
"Swinging Perl", JOptionPane.INFORMATION_MESSAGE);
return Integer.parseInt(str);
}
}
In simple cases like this, you don't even need to write a separate Java source file: you com-
bine all the code, Perl and Java alike, in one single file. You do not need to compile anything,
either; just execute it by typing:
perl Swinging.pl
(You can also add a string argument.) After a little churning, a Java message box pops up,
telling you that the distance between “Japh” and “Java” is 2. At the same time, your console
shows the string “Just another Perl hacker inside Java.” When you close the message box,
you get the final result “matcher: 2 (displayed from Perl).”
In between, your Perl program has created an instance of the Java class Showit by calling its
constructor. It then called that object's show() method to display a string from within Java. It
then proceeded to call the match() method, but this time, something more complicated hap-
pens: the Java code calls back into Perl, accessing method distance of module
Text::Levenshtein and passing it two strings as arguments. It receives the result, displays
it in a message box, and finally, for good measure, returns it to the Perl main program that it
had been called from.
Incidentally, the eval { } block around the method call is the Perlish way of catching ex-
ceptions. In this case, the exception is thrown from within Java.
If you restart the program, you will notice that startup time is much shorter, which is always
good news. Why is that so? On the first call, Inline::Java took the input apart, precom-
piled the Java part, and saved it to disk (usually, in a subdirectory called _Inline). On subse-
quent calls, it just makes sure that the Java source has not changed and then calls the class
file that is already on disk. (Of course, if you surreptitiously changed the Java code, it is re-
compiled just as automagically.) Behind the scenes, even stranger things are going on,
however. When the Perl script is executed, a Java server is constructed and started unbe-
Search WWH ::




Custom Search