⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tutorial.pod

📁 UNIX下perl实现代码
💻 POD
📖 第 1 页 / 共 2 页
字号:
=head1 NAMETutorial - Perl and Java=head1 SYNOPSISJava and Perl have different strengths and complement each other well.You can connect them at runtime with tools such as JPL, PJC, orActiveX. In theory, you can convert Perl to Java bytecode, andvice-versa.=head2 Note:Not actually a conversion.At this stage, we are generating Java opcodes by walking Perl's syntaxtree. This is very different from converting Perl to Java. It's a loteasier!=head1 1.1 Perl and Java, ComparedPerl offers rich text processing features, high-level network APIs,excellent database integration, and a centralized repository ofreusable code:=over 4=item *Regular expression engine is a powerful sub language that can performcomplex text manipulations and extract data.=item *Packages such as libwww-perl (LWP) and libnet are powerful, high-levelinterfaces to network functionality.=item *The Perl DBI is an interface to SQL data sources.=item *CPAN provides a centralized, organized archive of reusable code.=backJava has a powerful graphical API, has numerous embeddedimplementations, excellent database integration, but no singlerecognized repository of reusable code.=over 4=item *The Swing (JFC) toolkit is a powerful toolkit for developing userinterfaces. Java also boasts 2D and 3D graphics APIs.=item *Java comes in embedded flavors, such as:=over 4=item *Kaffe C<http://www.transvirtual.com/> - embedded implementations fordifferent platforms=item *Waba C<http://www.wabasoft.com/> - a subset of Java for Windows CE andPalmOS=item *It's embedded into web browsers (Netscape and MS Internet Explorer)=item *and more...=back=item *Java's JDBC is similar to Perl's DBI=item *Java has many different repositories of code. Efforts such as theGiant Java Tree C<http://www.gjt.org/> attempt to create a unifiedrepository.=back=head1 1.2 Opportunities to Combine Java and PerlYou have a Java program with a lot of data that needs to be parsed,filed, briefed, debriefed, and numbered.You want to build your GUI in Java, but let Perl do the heavy lifting.You've adopted the "Java is a systems language, Perl is a scriptinglanguage" paradigm, and it works for you.You're not sure which regex implementation to use:C<org.teeth.green.loony.raving.monster.regex.*;>C<com.zeppelin.regex.*;>You want the I<B<best of both worlds>>.=head1 1.3 Important Differences between Java and Perl=over 4=item *C<perl> compiles and executes programs each time you run them (unless youuse the Perl compiler).=item *C<javac> compiles programs in advance, C<java> runs them in the Javainterpreter.=item * The Java interpreter supports method overloading (methods can have thesame name, but are differentiated on the basis of their argumenttypes). Overloaded methods generally perform the same function, butmethods with a shorter argument list often use defaults:=back    // Draw a circle in the center of the screen    int drawCircle(int radius);    // Draw a circle at specified coordinates    int drawCircle(int radius, int h, int k);=over 4=item *The Perl interpreter doesn't support method overloading. In JPL, whenwe call Java from Perl, we need to use some tricks to specify the Javamethod we want to invoke. We'll learn about this when we see JPL'sC<getmeth> function.=back=head2 Note:At the time this presentation was prepared, JPL did not work with Perlfor Win32. However, JPL is in the core Perl distribution, and thereare plans to make it work with Perl for Win32.With that in mind, I'm presenting the JPL material first, because itis of interest to both Win32 and Unix Perl people. The Win32-specificstuff (alternatives to JPL) will come last. I won't be offended if theUnix people leave when I move to this section of the tutorial, sincethere is no Unix material in that section. I'm perfectly happy to takequestions between JPL and ActiveX sections. A subset of JPL now works on Win32. You can embed Java in Perl, butyou cannot embed Perl in Java (yet).=head1 2.1 JPL OverviewLet's look at an overview of JPL.=head2 2.1.1 Calling Perl from JavaWell-supported by JPL, but it is a complicated process:=over 4=item *The JPL preprocessor parses the I<.jpl> file and generates C codewrappers for Perl methods. It also generates Java and Perl sourcefiles.=item *The C compiler compiles the wrapper and links it to theI<libPerlInterpreter.so> shared library, producing a shared library forthe wrapper.=item *The Java compiler compiles the Java source file, which uses nativemethods to load the wrapper.=item *The wrapper connects the Java code to the Perl code in the Perl sourcefile.=backFortunately, a generic F<Makefile.PL> simplifies the process. This is aPerl script that generates a I<Makefile> for you.=head2 2.1.2 Calling Java from PerlThis works best when Perl is embedded within a Java program.The JNI Perl module creates and loads a JVM. There is no precompiler,nothing extra -- it's just a Perl module and extension.    B<A Problem, Though>. In theory, you can call Java from standalone    Perl programs, but this doesn't work because some implementations    of Java use a user-level threads package (green threads) that    override some functions in the C library. Perl is comfortable    using these functions, but Java is not happy using the standard C    library functions.So, with green threads, you can't reliably embed Java in a standalonePerl program.Many Java implementations now use native threads. JPL has been testedon Solaris with JDK 1.1.x and native threads, but not on Linux.=head2 Note:Oddly enough, this is the only way it works on Win32. On Unix, I've still had trouble, even with native threads. I mightneed to recompile perl with -DREENTRANT, but I'm not sure.=head1 2.2 Working with JPLHow to set up a JPL application, compile, and install it.=head2 2.2.1 Setting up a Project=over 4=item 1The I<install-jpl> script creates the I<setvars> script. Source theoutput of I<setvars> into your shell when you want to develop or runJPL applications.=item 2Create a directory with the name of your project, such asI<Frotz>. (if you want to use the generic F<Makefile.PL>, you need aseparate directory for each JPL class you create).=item 3Copy the generic F<Makefile.PL> into the project directory. TheI<jpl/Sample> directory in the Perl distribution includes the genericF<Makefile.PL>.=item 4Write a I<.jpl> program with the same name as the project (such asF<Frotz.jpl>)=back=head2 2.2.2 Compiling and Installing a ProjectType C<make> to compile the application, and C<make install> toinstall it. This installs the application in the I<jpl> directory youcreated when you installed JPL.    B<Beware>. The default I<jpl> directory is the same as the    directory you install it I<from>. If you go with the default and    delete your Perl source, you'll delete your JPL installation!Type C<java Frotz> (or the name you chose in step 2 of section 2.2.1)to run it=head2 2.2.3 What's in the jpl Directory?=over 4=item *B<libPerlInterpreter.so>: a shared library that loads the Perlinterpreter.=item *Compiled F<.class> files for JPL applications you have written.=item *Native code shared library wrappers for JPL applications you havewritten.=item *Perl scripts that contain the Perl code to load at runtime.=back    Beware. If you issue the C<make> command and then run the examples    in your development directory, you might be in for a surprise! If    the JPL directories come first in your CLASSPATH and    LD_LIBRARY_PATH, you'll keep running the installed, older version,    rather than the one you are developing=head2 Note:"Source" means to load it into your current shell, with somethinglike:C<eval-backtick-setvars-backtick>as opposed to just executing it, because then only the subshell getsthe environment vars.=head1 2.3 Calling Perl from JavaNow, we'll look at how you can invoke Perl from Java.=head2 2.3.1 Perl MethodsYou can put Perl methods in your F<.jpl> file. Perl methods aredeclared C<perl> and use double curly braces to make life easier onthe JPL preprocessor:    perl int perlMultiply(int a, int b) {{    my $result = $a * $b;    return $result;    }}In your Java code, you can invoke Perl methods like a Java method. Thenative code wrappers take care of running the Perl code:    public void invokePerlFunction() {        int x = 3;        int y = 6;        int retval = perlMultiply(x, y);        System.out.println(x + " * " + y + " = " + retval);    }class MethodDemo    class MethodDemo {    // A Perl method to multiply two numbers and    // return the result.    //    perl int perlMultiply(int a, int b) {{        my $result = $a * $b;        return $result;    }}    // A Java method to call the Perl function.    //    public void invokePerlFunction() {        int x = 3;        int y = 6;        int retval = perlMultiply(x, y);        System.out.println(x +" * "+ y +" = "+ retval);    }    public static void main(String[] args) {        MethodDemo demo = new MethodDemo();        demo.invokePerlFunction();        }    }=head2 Where did $self go?Don't worry, C<$self> is still there. JPL takes care of fetching it, aswell as all the other arguments:    perl int perlMultiply(int a, int b) {{        my $result = $a * $b;        return $result;    }}    perl void calculateProduct() {{        my $x = 3;        my $y = 6;        my $retval = $self->perlMultiply($x, $y);        print "$x * $y = $retval\n";    }}    B<Note>. JPL takes care of putting all the arguments, including    C<$self>, into variables. If you see a variable in the function    header, you will get a variable of the same name without having to    use C<shift> or C<@_>, guaranteed.NOTE:  I've added a line that prints the output of "ref dollar sign self"You'll see this when I run the demo.    class SelfDemo {    // A Perl method to multiply two values.    //    perl int perlMultiply(int a, int b) {{        my $result = $a * $b;        return $result;    }}    // A Perl method to invoke another Perl method.    //    perl void calculateProduct() {{        my $x = 3;        my $y = 6;        # Ahhh. There's our old friend, $self!        #        my $retval = $self->perlMultiply($x, $y);        # Display the results.        #        print "$x * $y = $retval\n";    }}    public static void main(String[] args) {        SelfDemo demo = new SelfDemo();        demo.calculateProduct();        }    }=head2 Passing ArraysIf you pass an array from Java into a Perl method, it arrives in theform of a scalar reference.Use the GetIntArrayElements() JNI function to convert that scalar intoan array of integers.    perl void min_max( int[] data ) {{        # Get the array elements        #        my @new_array = GetIntArrayElements( $data );        # Sort the array numerically        #        my @sorted = sort {$a <=> $b} @new_array;        print "Min: $sorted[0], ",        "Max: $sorted[$#sorted]\n";    }}    void minMaxDemo() {        int[] data = {101, 99, 42, 666, 23};        min_max( data );    }Some JNI Array Functions=over 4=item GetBooleanArrayElements( scalar)Converts scalar to an array of booleans.=item GetByteArrayElements( scalar )Converts scalar to an array of bytes.=item GetCharArrayElements( scalar )Converts scalar to an array of characters.=item GetShortArrayElements( scalar )Converts scalar to an array of short integers.=item GetIntArrayElements( scalar )Converts scalar to an array of integers.=item GetLongArrayElements( scalar )Converts scalar to an array of long integers.=item GetFloatArrayElements( scalar )Converts scalar to an array of floating point numbers.=item GetDoubleArrayElements( scalar )Converts scalar to an array of double precision numbers.=item GetArrayLength( scalar )Returns the length of the array.=backPerlTakesArray.jpl    // Show how to pass an array from Java to Perl.    //    public class PerlTakesArray {        perl void min_max( int[] data ) {{        # Get the array elements        #        my @new_array = GetIntArrayElements( $data );        # Sort the array numerically        #        my @sorted = sort {$a <=> $b} @new_array;        print "Min: $sorted[0], ",        "Max: $sorted[$#sorted]\n";    }}    void minMaxDemo() {        // Create an array and ask Perl to tell us        // the min and max values.        int[] data = {101, 99, 42, 666, 23};        min_max( data );    }    public static void main(String[] argv) {        PerlTakesArray demo = new PerlTakesArray();

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -