[6330] in Perl-Users-Digest

home help back first fref pref prev next nref lref last post

Perl-Users Digest, Issue: 952 Volume: 7

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Fri Feb 14 16:27:14 1997

Date: Fri, 14 Feb 97 13:01:47 -0800
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)

Perl-Users Digest           Fri, 14 Feb 1997     Volume: 7 Number: 952

Today's topics:
     Re: PerlXS <jasons@infinity.cs.unm.edu>
     Reference docs for CGI.PM?? <skbohler@ix.netcom.com>
     Re: regexp's in XEmacs vs. Perl <tchrist@mox.perl.com>
     Repost: Perl/SNMP mib load problem <jyoti@net.com>
     Searchable Database of Computer Language Software <heilborn@softwareage.com>
     Re: Sig{'ALRM'} question (Brian L. Matthews)
     Re: Sig{'ALRM'} question (Charles DeRykus)
     Re: subtle (to me) RE problem <fawcett@nynexst.com>
     Digest Administrivia (Last modified: 8 Jan 97) (Perl-Users-Digest Admin)

----------------------------------------------------------------------

Date: 14 Feb 1997 11:34:30 -0700
From: Jason Stewart <jasons@infinity.cs.unm.edu>
Subject: Re: PerlXS
Message-Id: <xjnu3nffd8p.fsf@infinity.cs.unm.edu>

The version of the perl xs tutorial you are using is way out of
date. None of the pages available over the internet that I've found
seem up to date. You should grab the latest version of perl from CPAN.
I'm using the 5.003_26 beta at the moment, but 5.004 should be out
sometime real soon - there just polishing things up.

I've included the latest version of perlxstut.html for your perusal...
jas.


<!-- $Id$ -->
<HTML><HEAD>
<CENTER><TITLE>perlxstut</TITLE></CENTER>
</HEAD>
<BODY><p><hr>

<H1> 
<A NAME="perlxstut_name_0">
NAME</A>
</H1>
perlXStut - Tutorial for XSUBs
<p><p><hr>

<H1> 
<A NAME="perlxstut_description_0">
DESCRIPTION</A>
</H1>
This tutorial will educate the reader on the steps involved in creating
a Perl extension.  The reader is assumed to have access to 
<A HREF="perlguts.html">
the <EM>perlguts</EM> manpage</A>
 and

<A HREF="perlxs.html">
the <EM>perlxs</EM> manpage</A>
 .
<p>This tutorial starts with very simple examples and becomes more complex,
with each new example adding new features.  Certain concepts may not be
completely explained until later in the tutorial to ease the
reader slowly into building extensions.
<p>
<H2> 
<A NAME="perlxstut_version_0">
VERSION CAVEAT</A>
</H2>
This tutorial tries hard to keep up with the latest development versions
of Perl.  This often means that it is sometimes in advance of the latest
released version of Perl, and that certain features described here might
not work on earlier versions.  This section will keep track of when various
features were added to Perl 5.
<p>
<UL>
<LI>In versions of Perl 5.002 prior to the gamma version, the test script
in Example 1 will not function properly.  You need to change the "use
lib" line to read:
<p>
<XMP>
        use lib './blib';

</XMP>
<p>
<LI>In versions of Perl 5.002 prior to version beta 3, the line in the .xs file
about ``PROTOTYPES: DISABLE'' will cause a compiler error.  Simply remove that
line from the file.
<p>
<LI>In versions of Perl 5.002 prior to version 5.002b1h, the test.pl file was not
automatically created by h2xs.  This means that you cannot say ``make test''
to run the test script.  You will need to add the following line before the
``use extension'' statement:
<p>
<XMP>
        use lib './blib';

</XMP>
<p>
<LI>In versions 5.000 and 5.001, instead of using the above line, you will need
to use the following line:
<p>
<XMP>
        BEGIN { unshift(@INC, "./blib") }

</XMP>
<p>
<LI>This document assumes that the executable named ``perl'' is Perl version 5.  
Some systems may have installed Perl version 5 as ``perl5''.
<p>
</UL>

<H2> 
<A NAME="perlxstut_dynamic_0">
DYNAMIC VERSUS STATIC</A>
</H2>
It is commonly thought that if a system does not have the capability to
load a library dynamically, you cannot build XSUBs.  This is incorrect.
You <EM>can</EM> build them, but you must link the XSUB's subroutines with the
rest of Perl, creating a new executable.  This situation is similar to
Perl 4.
<p>This tutorial can still be used on such a system.  The XSUB build mechanism
will check the system and build a dynamically-loadable library if possible,
or else a static library and then, optionally, a new statically-linked
executable with that static library linked in.
<p>Should you wish to build a statically-linked executable on a system which
can dynamically load libraries, you may, in all the following examples,
where the command ``make'' with no arguments is executed, run the command
``make perl'' instead.
<p>If you have generated such a statically-linked executable by choice, then
instead of saying ``make test'', you should say ``make test_static''.  On systems
that cannot build dynamically-loadable libraries at all, simply saying "make
test" is sufficient.
<p>
<H2> 
<A NAME="perlxstut_example_0">
EXAMPLE 1</A>
</H2>
Our first extension will be very simple.  When we call the routine in the
extension, it will print out a well-known message and return.
<p>Run <CODE>h2xs -A -n Mytest</CODE>.  This creates a directory named Mytest, possibly under
ext/ if that directory exists in the current working directory.  Several files
will be created in the Mytest dir, including MANIFEST, Makefile.PL, Mytest.pm,
Mytest.xs, test.pl, and Changes.
<p>The MANIFEST file contains the names of all the files created.
<p>The file Makefile.PL should look something like this:
<p>
<XMP>
        use ExtUtils::MakeMaker;
        # See lib/ExtUtils/MakeMaker.pm for details of how to influence
        # the contents of the Makefile that is written.
        WriteMakefile(
            'NAME'      => 'Mytest',
            'VERSION_FROM' => 'Mytest.pm', # finds $VERSION
            'LIBS'      => [''],   # e.g., '-lm'
            'DEFINE'    => '',     # e.g., '-DHAVE_SOMETHING'
            'INC'       => '',     # e.g., '-I/usr/include/other'
        );

</XMP>
<p>The file Mytest.pm should start with something like this:
<p>
<XMP>
        package Mytest;
        require Exporter;
        require DynaLoader;
        @ISA = qw(Exporter DynaLoader);
        # Items to export into callers namespace by default. Note: do not export
        # names by default without a very good reason. Use EXPORT_OK instead.
        # Do not simply export all your public functions/methods/constants.
        @EXPORT = qw(
        );
        $VERSION = '0.01';
        bootstrap Mytest $VERSION;
        # Preloaded methods go here.
        # Autoload methods go after __END__, and are processed by the autosplit program.
        1;
        __END__
        # Below is the stub of documentation for your module. You better edit it!

</XMP>
<p>And the Mytest.xs file should look something like this:
<p>
<XMP>
        #ifdef __cplusplus
        extern "C" {
        #endif
        #include "EXTERN.h"
        #include "perl.h"
        #include "XSUB.h"
        #ifdef __cplusplus
        }
        #endif
        
        PROTOTYPES: DISABLE
        MODULE = Mytest         PACKAGE = Mytest

</XMP>
<p>Let's edit the .xs file by adding this to the end of the file:
<p>
<XMP>
        void
        hello()
                CODE:
                printf("Hello, world!\n");

</XMP>
<p>Now we'll run ``perl Makefile.PL''.  This will create a real Makefile,
which make needs.  Its output looks something like:
<p>
<XMP>
        % perl Makefile.PL
        Checking if your kit is complete...
        Looks good
        Writing Makefile for Mytest
        %

</XMP>
<p>Now, running make will produce output that looks something like this
(some long lines shortened for clarity):
<p>
<XMP>
        % make
        umask 0 && cp Mytest.pm ./blib/Mytest.pm
        perl xsubpp -typemap typemap Mytest.xs >Mytest.tc && mv Mytest.tc Mytest.c
        cc -c Mytest.c
        Running Mkbootstrap for Mytest ()
        chmod 644 Mytest.bs
        LD_RUN_PATH="" ld -o ./blib/PA-RISC1.1/auto/Mytest/Mytest.sl -b Mytest.o
        chmod 755 ./blib/PA-RISC1.1/auto/Mytest/Mytest.sl
        cp Mytest.bs ./blib/PA-RISC1.1/auto/Mytest/Mytest.bs
        chmod 644 ./blib/PA-RISC1.1/auto/Mytest/Mytest.bs

</XMP>
<p>Now, although there is already a test.pl template ready for us, for this
example only, we'll create a special test script.  Create a file called hello
that looks like this:
<p>
<XMP>
        #! /opt/perl5/bin/perl
        
        use ExtUtils::testlib;
        
        use Mytest;
        
        Mytest::hello();

</XMP>
<p>Now we run the script and we should see the following output:
<p>
<XMP>
        % perl hello
        Hello, world!
        %

</XMP>
<p>
<H2> 
<A NAME="perlxstut_example_1">
EXAMPLE 2</A>
</H2>
Now let's add to our extension a subroutine that will take a single argument
and return 1 if the argument is even, 0 if the argument is odd.
<p>Add the following to the end of Mytest.xs:
<p>
<XMP>
        int
        is_even(input)
                int     input
                CODE:
                RETVAL = (input % 2 == 0);
                OUTPUT:
                RETVAL

</XMP>
<p>There does not need to be white space at the start of the ``int input'' line,
but it is useful for improving readability.  The semi-colon at the end of
that line is also optional.
<p>Any white space may be between the ``int'' and ``input''.  It is also okay for
the four lines starting at the ``CODE:'' line to not be indented.  However,
for readability purposes, it is suggested that you indent them 8 spaces
(or one normal tab stop).
<p>Now re-run make to rebuild our new shared library.
<p>Now perform the same steps as before, generating a Makefile from the
Makefile.PL file, and running make.
<p>To test that our extension works, we now need to look at the
file test.pl.  This file is set up to imitate the same kind of testing
structure that Perl itself has.  Within the test script, you perform a
number of tests to confirm the behavior of the extension, printing ``ok''
when the test is correct, ``not ok'' when it is not.  Change the print
statement in the BEGIN block to print ``1..4'', and add the following code
to the end of the file:
<p>
<XMP>
        print &Mytest::is_even(0) == 1 ? "ok 2" : "not ok 2", "\n";
        print &Mytest::is_even(1) == 0 ? "ok 3" : "not ok 3", "\n";
        print &Mytest::is_even(2) == 1 ? "ok 4" : "not ok 4", "\n";

</XMP>
<p>We will be calling the test script through the command ``make test''.  You
should see output that looks something like this:
<p>
<XMP>
        % make test
        PERL_DL_NONLAZY=1 /opt/perl5.002b2/bin/perl (lots of -I arguments) test.pl
        1..4
        ok 1
        ok 2
        ok 3
        ok 4
        %

</XMP>
<p>
<H2> 
<A NAME="perlxstut_what_0">
WHAT HAS GONE ON?</A>
</H2>
The program h2xs is the starting point for creating extensions.  In later
examples we'll see how we can use h2xs to read header files and generate
templates to connect to C routines.
<p>h2xs creates a number of files in the extension directory.  The file
Makefile.PL is a perl script which will generate a true Makefile to build
the extension.  We'll take a closer look at it later.
<p>The files &lt;extension&gt;.pm and &lt;extension&gt;.xs contain the meat
of the extension.
The .xs file holds the C routines that make up the extension.  The .pm file
contains routines that tell Perl how to load your extension.
<p>Generating and invoking the Makefile created a directory blib (which stands
for ``build library'') in the current working directory.  This directory will
contain the shared library that we will build.  Once we have tested it, we
can install it into its final location.
<p>Invoking the test script via ``make test'' did something very important.  It
invoked perl with all those 
<A HREF="perlrun.html#perlrun_i_1">-I</A>
 arguments so that it could find the various
files that are part of the extension.
<p>It is <EM>very</EM> important that while you are still testing extensions that
you use ``make test''.  If you try to run the test script all by itself, you
will get a fatal error.
<p>Another reason it is important to use ``make test'' to run your test script
is that if you are testing an upgrade to an already-existing version, using
``make test'' insures that you use your new extension, not the already-existing
version.
<p>When Perl sees a 
<A HREF="perlfunc.html#perlfunc_use_3">use extension;</A>
, it searches for a file with the same name
as the use'd extension that has a .pm suffix.  If that file cannot be found,
Perl dies with a fatal error.  The default search path is contained in the

<A HREF="perlvar.html#perlvar_inc_0">@INC</A>
 array.
<p>In our case, Mytest.pm tells perl that it will need the Exporter and Dynamic
Loader extensions.  It then sets the <STRONG>@ISA</STRONG> and <STRONG>@EXPORT</STRONG> arrays and the <STRONG>$VERSION</STRONG>
scalar; finally it tells perl to bootstrap the module.  Perl will call its
dynamic loader routine (if there is one) and load the shared library.
<p>The two arrays that are set in the .pm file are very important.  The <STRONG>@ISA</STRONG>
array contains a list of other packages in which to search for methods (or
subroutines) that do not exist in the current package.  The <STRONG>@EXPORT</STRONG> array
tells Perl which of the extension's routines should be placed into the
calling package's namespace.
<p>It's important to select what to export carefully.  Do NOT export method names
and do NOT export anything else <EM>by default</EM> without a good reason.
<p>As a general rule, if the module is trying to be object-oriented then don't
export anything.  If it's just a collection of functions then you can export
any of the functions via another array, called <STRONG>@EXPORT_OK</STRONG>.
<p>See 
<A HREF="perlmod.html">
the <EM>perlmod</EM> manpage</A>
 for more information.
<p>The <STRONG>$VERSION</STRONG> variable is used to ensure that the .pm file and the shared
library are ``in sync'' with each other.  Any time you make changes to
the .pm or .xs files, you should increment the value of this variable.
<p>
<H2> 
<A NAME="perlxstut_writing_0">
WRITING GOOD TEST SCRIPTS</A>
</H2>
The importance of writing good test scripts cannot be overemphasized.  You
should closely follow the ``ok/not ok'' style that Perl itself uses, so that
it is very easy and unambiguous to determine the outcome of each test case.
When you find and fix a bug, make sure you add a test case for it.
<p>By running ``make test'', you ensure that your test.pl script runs and uses
the correct version of your extension.  If you have many test cases, you
might want to copy Perl's test style.  Create a directory named ``t'', and
ensure all your test files end with the suffix ``.t''.  The Makefile will
properly run all these test files.
<p>
<H2> 
<A NAME="perlxstut_example_2">
EXAMPLE 3</A>
</H2>
Our third extension will take one argument as its input, round off that
value, and set the <EM>argument</EM> to the rounded value.
<p>Add the following to the end of Mytest.xs:
<p>
<XMP>
        void
        round(arg)
                double  arg
                CODE:
                if (arg > 0.0) {
                        arg = floor(arg + 0.5);
                } else if (arg < 0.0) {
                        arg = ceil(arg - 0.5);
                } else {
                        arg = 0.0;
                }
                OUTPUT:
                arg

</XMP>
<p>Edit the Makefile.PL file so that the corresponding line looks like this:
<p>
<XMP>
        'LIBS'      => ['-lm'],   # e.g., '-lm'

</XMP>
<p>Generate the Makefile and run make.  Change the BEGIN block to print out
``1..9'' and add the following to test.pl:
<p>
<XMP>
        $i = -1.5; &Mytest::round($i); print $i == -2.0 ? "ok 5" : "not ok 5", "\n";
        $i = -1.1; &Mytest::round($i); print $i == -1.0 ? "ok 6" : "not ok 6", "\n";
        $i = 0.0; &Mytest::round($i); print $i == 0.0 ? "ok 7" : "not ok 7", "\n";
        $i = 0.5; &Mytest::round($i); print $i == 1.0 ? "ok 8" : "not ok 8", "\n";
        $i = 1.2; &Mytest::round($i); print $i == 1.0 ? "ok 9" : "not ok 9", "\n";

</XMP>
<p>Running ``make test'' should now print out that all nine tests are okay.
<p>You might be wondering if you can round a constant.  To see what happens, add
the following line to test.pl temporarily:
<p>
<XMP>
        &Mytest::round(3);

</XMP>
<p>Run ``make test'' and notice that Perl dies with a fatal error.  Perl won't let
you change the value of constants!
<p>
<H2> 
<A NAME="perlxstut_what_s_0">
WHAT'S NEW HERE?</A>
</H2>
Two things are new here.  First, we've made some changes to Makefile.PL.
In this case, we've specified an extra library to link in, the math library
libm.  We'll talk later about how to write XSUBs that can call every routine
in a library.
<p>Second, the value of the function is being passed back not as the function's
return value, but through the same variable that was passed into the function.
<p>
<H2> 
<A NAME="perlxstut_input_0">
INPUT AND OUTPUT PARAMETERS</A>
</H2>
You specify the parameters that will be passed into the XSUB just after you
declare the function return value and name.  Each parameter line starts with
optional white space, and may have an optional terminating semicolon.
<p>The list of output parameters occurs after the OUTPUT: directive.  The use
of RETVAL tells Perl that you wish to send this value back as the return
value of the XSUB function.  In Example 3, the value we wanted returned was
contained in the same variable we passed in, so we listed it (and not RETVAL)
in the OUTPUT: section.
<p>
<H2> 
<A NAME="perlxstut_the_0">
THE XSUBPP COMPILER</A>
</H2>
The compiler xsubpp takes the XS code in the .xs file and converts it into
C code, placing it in a file whose suffix is .c.  The C code created makes
heavy use of the C functions within Perl.
<p>
<H2> 
<A NAME="perlxstut_the_1">
THE TYPEMAP FILE</A>
</H2>
The xsubpp compiler uses rules to convert from Perl's data types (scalar,
array, etc.) to C's data types (int, char *, etc.).  These rules are stored
in the typemap file (<STRONG>$PERLLIB</STRONG>/ExtUtils/typemap).  This file is split into
three parts.
<p>The first part attempts to map various C data types to a coded flag, which
has some correspondence with the various Perl types.  The second part contains
C code which xsubpp uses for input parameters.  The third part contains C
code which xsubpp uses for output parameters.  We'll talk more about the
C code later.
<p>Let's now take a look at a portion of the .c file created for our extension.
<p>
<XMP>
        XS(XS_Mytest_round)
        {
            dXSARGS;
            if (items != 1)
                croak("Usage: Mytest::round(arg)");
            {
                double  arg = (double)SvNV(ST(0));      /* XXXXX */
                if (arg > 0.0) {
                        arg = floor(arg + 0.5);
                } else if (arg < 0.0) {
                        arg = ceil(arg - 0.5);
                } else {
                        arg = 0.0;
                }
                sv_setnv(ST(0), (double)arg);   /* XXXXX */
            }
            XSRETURN(1);
        }

</XMP>
<p>Notice the two lines marked with ``XXXXX''.  If you check the first section of
the typemap file, you'll see that doubles are of type T_DOUBLE.  In the
INPUT section, an argument that is T_DOUBLE is assigned to the variable
arg by calling the routine SvNV on something, then casting it to double,
then assigned to the variable arg.  Similarly, in the OUTPUT section,
once arg has its final value, it is passed to the sv_setnv function to
be passed back to the calling subroutine.  These two functions are explained
in 
<A HREF="perlguts.html">
the <EM>perlguts</EM> manpage</A>
; we'll talk more later about what that ``ST(0)'' means in the
section on the argument stack.
<p>
<H2> 
<A NAME="perlxstut_warning_0">
WARNING</A>
</H2>
In general, it's not a good idea to write extensions that modify their input
parameters, as in Example 3.  However, to accommodate better calling
pre-existing C routines, which often do modify their input parameters,
this behavior is tolerated.  The next example will show how to do this.
<p>
<H2> 
<A NAME="perlxstut_example_3">
EXAMPLE 4</A>
</H2>
In this example, we'll now begin to write XSUB's that will interact with
pre-defined C libraries.  To begin with, we will build a small library of
our own, then let h2xs write our .pm and .xs files for us.
<p>Create a new directory called Mytest2 at the same level as the directory
Mytest.  In the Mytest2 directory, create another directory called mylib,
and cd into that directory.
<p>Here we'll create some files that will generate a test library.  These will
include a C source file and a header file.  We'll also create a Makefile.PL
in this directory.  Then we'll make sure that running make at the Mytest2
level will automatically run this Makefile.PL file and the resulting Makefile.
<p>In the testlib directory, create a file mylib.h that looks like this:
<p>
<XMP>
        #define TESTVAL 4
        extern double   foo(int, long, const char*);

</XMP>
<p>Also create a file mylib.c that looks like this:
<p>
<XMP>
        #include <stdlib.h>
        #include "./mylib.h"
        
        double
        foo(a, b, c)
        int             a;
        long            b;
        const char *    c;
        {
                return (a + b + atof(c) + TESTVAL);
        }

</XMP>
<p>And finally create a file Makefile.PL that looks like this:
<p>
<XMP>
        use ExtUtils::MakeMaker;
        $Verbose = 1;
        WriteMakefile(
            NAME      => 'Mytest2::mylib',
            SKIP      => [qw(all static static_lib dynamic dynamic_lib)],
            clean     => {'FILES' => 'libmylib$(LIB_EXT)'},
        );
        sub MY::top_targets {
                '
        all :: static
        static ::       libmylib$(LIB_EXT)
        libmylib$(LIB_EXT): $(O_FILES)
                $(AR) cr libmylib$(LIB_EXT) $(O_FILES)
                $(RANLIB) libmylib$(LIB_EXT)
        ';
        }

</XMP>
<p>We will now create the main top-level Mytest2 files.  Change to the directory
above Mytest2 and run the following command:
<p>
<XMP>
        % h2xs -O -n Mytest2 ./Mytest2/mylib/mylib.h

</XMP>
<p>This will print out a warning about overwriting Mytest2, but that's okay.
Our files are stored in Mytest2/mylib, and will be untouched.
<p>The normal Makefile.PL that h2xs generates doesn't know about the mylib
directory.  We need to tell it that there is a subdirectory and that we
will be generating a library in it.  Let's add the following key-value
pair to the WriteMakefile call:
<p>
<XMP>
        'MYEXTLIB' => 'mylib/libmylib$(LIB_EXT)',

</XMP>
<p>and a new replacement subroutine too:
<p>
<XMP>
        sub MY::postamble {
        '
        $(MYEXTLIB): mylib/Makefile
                cd mylib && $(MAKE)
        ';
        }

</XMP>
<p>(Note: Most makes will require that there be a tab character that indents
the line ``cd mylib &amp;&amp; 
<A HREF="perlvar.html#perlvar__26">$(</A>
MAKE)'', similarly for the Makefile in the
subdirectory.)
<p>Let's also fix the MANIFEST file so that it accurately reflects the contents
of our extension.  The single line that says ``mylib'' should be replaced by
the following three lines:
<p>
<XMP>
        mylib/Makefile.PL
        mylib/mylib.c
        mylib/mylib.h

</XMP>
<p>To keep our namespace nice and unpolluted, edit the .pm file and change
the lines setting <STRONG>@EXPORT</STRONG> to <STRONG>@EXPORT_OK</STRONG> (there are two: one in the line
beginning ``use vars'' and one setting the array itself).  Finally, in the
 .xs file, edit the #include line to read:
<p>
<XMP>
        #include "mylib/mylib.h"

</XMP>
<p>And also add the following function definition to the end of the .xs file:
<p>
<XMP>
        double
        foo(a,b,c)
                int             a
                long            b
                const char *    c
                OUTPUT:
                RETVAL

</XMP>
<p>Now we also need to create a typemap file because the default Perl doesn't
currently support the const char * type.  Create a file called typemap and
place the following in it:
<p>
<XMP>
        const char *    T_PV

</XMP>
<p>Now run perl on the top-level Makefile.PL.  Notice that it also created a
Makefile in the mylib directory.  Run make and see that it does cd into
the mylib directory and run make in there as well.
<p>Now edit the test.pl script and change the BEGIN block to print ``1..4'',
and add the following lines to the end of the script:
<p>
<XMP>
        print &Mytest2::foo(1, 2, "Hello, world!") == 7 ? "ok 2\n" : "not ok 2\n";
        print &Mytest2::foo(1, 2, "0.0") == 7 ? "ok 3\n" : "not ok 3\n";
        print abs(&Mytest2::foo(0, 0, "-3.4") - 0.6) <= 0.01 ? "ok 4\n" : "not ok 4\n";

</XMP>
<p>(When dealing with floating-point comparisons, it is often useful not to check
for equality, but rather the difference being below a certain epsilon factor,
0.01 in this case)
<p>Run ``make test'' and all should be well.
<p>
<H2> 
<A NAME="perlxstut_what_1">
WHAT HAS HAPPENED HERE?</A>
</H2>
Unlike previous examples, we've now run h2xs on a real include file.  This
has caused some extra goodies to appear in both the .pm and .xs files.
<p>
<UL>
<LI>In the .xs file, there's now a #include declaration with the full path to
the mylib.h header file.
<p>
<LI>There's now some new C code that's been added to the .xs file.  The purpose
of the <CODE>constant</CODE> routine is to make the values that are #define'd in the
header file available to the Perl script (in this case, by calling
<CODE>&amp;main::TESTVAL</CODE>).  There's also some XS code to allow calls to the
<CODE>constant</CODE> routine.
<p>
<LI>The .pm file has exported the name TESTVAL in the <STRONG>@EXPORT</STRONG> array.  This
could lead to name clashes.  A good rule of thumb is that if the #define
is going to be used by only the C routines themselves, and not by the user,
they should be removed from the <STRONG>@EXPORT</STRONG> array.  Alternately, if you don't
mind using the ``fully qualified name'' of a variable, you could remove most
or all of the items in the <STRONG>@EXPORT</STRONG> array.
<p>
<LI>If our include file contained #include directives, these would not be
processed at all by h2xs.  There is no good solution to this right now.
<p>
</UL>
We've also told Perl about the library that we built in the mylibsubdirectory.  That required the addition of only the MYEXTLIB variable
to the WriteMakefile call and the replacement of the postamble subroutine
to cd into the subdirectory and run make.  The Makefile.PL for the
library is a bit more complicated, but not excessively so.  Again we
replaced the postamble subroutine to insert our own code.  This code
specified simply that the library to be created here was a static
archive (as opposed to a dynamically loadable library) and provided the
commands to build it.
<p>
<H2> 
<A NAME="perlxstut_specifying_0">
SPECIFYING ARGUMENTS TO XSUBPP</A>
</H2>
With the completion of Example 4, we now have an easy way to simulate some
real-life libraries whose interfaces may not be the cleanest in the world.
We shall now continue with a discussion of the arguments passed to the
xsubpp compiler.
<p>When you specify arguments in the .xs file, you are really passing three
pieces of information for each one listed.  The first piece is the order
of that argument relative to the others (first, second, etc).  The second
is the type of argument, and consists of the type declaration of the
argument (e.g., int, char*, etc).  The third piece is the exact way in
which the argument should be used in the call to the library function
from this XSUB.  This would mean whether or not to place a ``&amp;'' before
the argument or not, meaning the argument expects to be passed the address
of the specified data type.
<p>There is a difference between the two arguments in this hypothetical function:
<p>
<XMP>
        int
        foo(a,b)
                char    &a
                char *  b

</XMP>
<p>The first argument to this function would be treated as a char and assigned
to the variable a, and its address would be passed into the function foo.
The second argument would be treated as a string pointer and assigned to the
variable b.  The <EM>value</EM> of b would be passed into the function foo.  The
actual call to the function foo that xsubpp generates would look like this:
<p>
<XMP>
        foo(&a, b);

</XMP>
<p>Xsubpp will identically parse the following function argument lists:
<p><UL><LI>	char	&a</LI>
<LI>	char&a</LI>
<LI>	char	& a</LI>
</UL>
<p>However, to help ease understanding, it is suggested that you place a ``&amp;''
next to the variable name and away from the variable type), and place a
``*'' near the variable type, but away from the variable name (as in the
complete example above).  By doing so, it is easy to understand exactly
what will be passed to the C function -- it will be whatever is in the
``last column''.
<p>You should take great pains to try to pass the function the type of variable
it wants, when possible.  It will save you a lot of trouble in the long run.
<p>
<H2> 
<A NAME="perlxstut_the_2">
THE ARGUMENT STACK</A>
</H2>
If we look at any of the C code generated by any of the examples except
example 1, you will notice a number of references to ST(n), where n is
usually 0.  The ``ST'' is actually a macro that points to the n'th argument
on the argument stack.  ST(0) is thus the first argument passed to the
XSUB, ST(1) is the second argument, and so on.
<p>When you list the arguments to the XSUB in the .xs file, that tells xsubpp
which argument corresponds to which of the argument stack (i.e., the first
one listed is the first argument, and so on).  You invite disaster if you
do not list them in the same order as the function expects them.
<p>
<H2> 
<A NAME="perlxstut_extending_0">
EXTENDING YOUR EXTENSION</A>
</H2>
Sometimes you might want to provide some extra methods or subroutines
to assist in making the interface between Perl and your extension simpler
or easier to understand.  These routines should live in the .pm file.
Whether they are automatically loaded when the extension itself is loaded
or loaded only when called depends on where in the .pm file the subroutine
definition is placed.
<p>
<H2> 
<A NAME="perlxstut_documenting_0">
DOCUMENTING YOUR EXTENSION</A>
</H2>
There is absolutely no excuse for not documenting your extension.
Documentation belongs in the .pm file.  This file will be fed to pod2man,
and the embedded documentation will be converted to the man page format,
then placed in the blib directory.  It will be copied to Perl's man
page directory when the extension is installed.
<p>You may intersperse documentation and Perl code within the .pm file.
In fact, if you want to use method autoloading, you must do this,
as the comment inside the .pm file explains.
<p>See 
<A HREF="perlpod.html">
the <EM>perlpod</EM> manpage</A>
 for more information about the pod format.
<p>
<H2> 
<A NAME="perlxstut_installing_0">
INSTALLING YOUR EXTENSION</A>
</H2>
Once your extension is complete and passes all its tests, installing it
is quite simple: you simply run ``make install''.  You will either need 
to have write permission into the directories where Perl is installed,
or ask your system administrator to run the make for you.
<p>
<H2> 
<A NAME="perlxstut_see_0">
SEE ALSO</A>
</H2>
For more information, consult 
<A HREF="perlguts.html">
the <EM>perlguts</EM> manpage</A>
, 
<A HREF="perlxs.html">
the <EM>perlxs</EM> manpage</A>
, 
<A HREF="perlmod.html">
the <EM>perlmod</EM> manpage</A>
,
and 
<A HREF="perlpod.html">
the <EM>perlpod</EM> manpage</A>
 .
<p>
<H2> 
<A NAME="perlxstut_author_0">
Author</A>
</H2>
Jeff Okamoto &lt;<EM><A HREF="MAILTO:okamoto@corp.hp.com">okamoto@corp.hp.com</A></EM>&gt;
<p>Reviewed and assisted by Dean Roehrich, Ilya Zakharevich, Andreas Koenig,
and Tim Bunce.
<p>
<H2> 
<A NAME="perlxstut_last_0">
Last Changed</A>
</H2>
1996/7/10
<p>
</BODY>
</HTML>


------------------------------

Date: 14 Feb 1997 20:36:49 GMT
From: "Stephen K. Bohler" <skbohler@ix.netcom.com>
Subject: Reference docs for CGI.PM??
Message-Id: <01bc1ab6$aa8452e0$9ae72ac2@steve>

I was wondering if anyone knew where I can find a rather exhaustive
reference guide on all of the available functions available in CGI.pm?

I've looked at:
http://www.genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html

 ...but it only covered some functions.

Thanks in advance,
Steve

-- 
Stephen Bohler
Oxford
United Kingdom


------------------------------

Date: 14 Feb 1997 18:45:55 GMT
From: Tom Christiansen <tchrist@mox.perl.com>
Subject: Re: regexp's in XEmacs vs. Perl
Message-Id: <5e2bt3$3km$2@csnews.cs.colorado.edu>

 [courtesy cc of this posting sent to cited author via email]

In comp.lang.perl.misc, 
    Hrvoje Niksic <hniksic@srce.hr> writes:
:> While presumably one could do simple things like translate '\s' to
:> '[ \t\n\r]', it would be require significant work to get some of
:> the more useful Perl regexps.  Even to implement the \s translation
:> perfectly one would need a regular expression parser so that
:> [\sxyz] changes to [ \t\n\rxyz].
:
:Whatever are you talking about??  Haven't you ever looked at Emacs
:syntax tables?  Perl \s is the same as Emacs \s-.  Emacs also has \s_,
:\sw, \S<something>, etc.  Look up the regexp section of the manual.

I never realized that emacs was happy to use syntax classes within
character classes, as perl can do with things like [\-.\w\s].

--tom
-- 
	Tom Christiansen	tchrist@jhereg.perl.com


	"EMACS belongs in <sys/errno.h>: Editor Too Big!" -me


------------------------------

Date: Thu, 13 Feb 1997 15:53:07 -0800
From: Jyoti Patel <jyoti@net.com>
Subject: Repost: Perl/SNMP mib load problem
Message-Id: <3303A963.79D4@net.com>

I posted this a week ago but did not receive any replies
so here's another try.

I am using Perl 5.003, cmu_snmp2.1.2, SNMP1.6

With this setup, I am trying to write a perl script
to load a couple of mibs and then to do sets and gets.
I am experiencing problems in loading two mibs back to
back. I don't know if Perl can't handle loading of multiple
mibs or if the mib syntax is a problem.

Can anyone please tell me what's going on. Does Perl require
it's Mibs to be in one giant file?

It loads one mib then I get the following error:
-----------------------------------------------------------------
mombasa{jyoti}100: ./test1.pl
initializing MIB...done
Use of uninitialized value at /usr/thirdParty/perl/lib/site_perl/SNMP.pm
line 65.
initializing MIB...The mib description doesn't seem to be consistent.
Some nodes couldn't be linked under the "iso" tree.
these nodes are left:
<it goes on to list all the attributes defined in the mib. eg>
 ....
NodeConfigNodeNumber ::= { NodeConfigEntry 2 } (134)
NodeConfigDomainNumber ::= { NodeConfigEntry 1 } (134)
NodeConfigTable ::= { node 1 } (14)
NodeConfigEntry ::= { NodeConfigTable 1 } (1)
----------------------------------------------------------------

The Script (test1.pl) is simply:

#!/usr/thirdParty/perl/bin/perl
 
# required statement
use SNMP 1.6;
 
# if mib not autoloaded, set auto_init_mib to 0 and setmib name
$SNMP::auto_init_mib = 0;
SNMP::setMib('mibs/generic.mib');
SNMP::setMib('mibs/nodeConfig.mib');
 
---------------------------------------------------------------


Any help is greatly appreciated

Thanks
-- Jyoti

      			     wwwww
                            ( @ @ ) 
+-+----------------------oOO--(_)--OOo--------------+-+
|o| Jyoti Patel                 Phone:(415)780-5717 |o|
| | N.E.T			Fax:  (415)780-5001 | |
| | 800 SAGINAW DRIVE           Email:jyoti@net.com | |
| | REDWOOD CITY, CA 94063                          | |
|o| USA                   ooo0  0ooo                |o|
+-+-----------------------(  )--(  )----------------+-+
     	                   \_)  (_/


------------------------------

Date: Fri, 14 Feb 1997 14:04:00 +0000
From: "George H. Heilborn" <heilborn@softwareage.com>
Subject: Searchable Database of Computer Language Software
Message-Id: <330470D0.24FB@softwareage.com>

Software Age (http://www.softwareage.com) has an easily searchable 
database of over 2,200 software products, information on 800 software 
developers, a calendar of software-related conferences and expositions, 
and a list of trade associations and user groups.  

Software users can type in a short description of the type of software 
product they are interested in, and receive a list of products meeting 
those criteria.  Each product on the resulting list has a hyperlink to 
the product page within the developer's site which gives detailed 
information on that product.  In addition, the listing has a hyperlink 
to another page giving contact information for the developer.  Where 
available, sales and technical support phone numbers and e-mail 
addresses are supplied.

Access to the Web site and use of the databases at Software Age are free 
to users.  Listings of companies, products, and events are free to 
software publishers and developers.

Software publishers and developers can list their products via the 
electronic entry form on the Software Age Web site at 
(http://www.softwareage.com/ACGI/AddProduct.html).

If you find Software Age useful, BOOKMARK the site for future reference.


------------------------------

Date: 14 Feb 1997 10:45:58 -0800
From: blm@halcyon.com (Brian L. Matthews)
Subject: Re: Sig{'ALRM'} question
Message-Id: <5e2bt6$7hg$1@halcyon.com>

In article <E5JD5K.62A@actcom.co.il>, Sara Young <syoung@actcom.co.il> wrote:
|Is it possible to cause an alarm to do the equivalent of a next statement?

Try something like:

$sawalarm = 0;

$SIG{'ALRM'} = sub { $sawalarm = 1; };

alarm 42;

while (...)
{
    $sawalarm = 0, alarm 23, next if $sawalarm;
    ...
}

Brian
-- 
Brian L. Matthews				Illustration Works, Inc.
	For top quality, stock commercial illustration, visit:
		  http://www.halcyon.com/artstock


------------------------------

Date: Fri, 14 Feb 1997 18:56:16 GMT
From: ced@bcstec.ca.boeing.com (Charles DeRykus)
Subject: Re: Sig{'ALRM'} question
Message-Id: <E5LwLt.II2@bcstec.ca.boeing.com>

In article <E5JD5K.62A@actcom.co.il>, Sara Young <syoung@actcom.co.il> wrote:
 >Is it possible to cause an alarm to do the equivalent of a next statement?
 >
 >I have a loop that does something.  If there is an alarm, I want it to go
 >on to the next iteration.
 >
 >I am running on System V.
 >

I


Perhaps something along these lines if you've got a 
fairly recent perl:


my $seconds = <your interval>; 
my $ring = "ring";
$SIG{ALRM} = sub { die $ring };

LOOP: {
    alarm $seconds; 
    eval {      # rest of loop within eval  
      ....     
      ....  
    };
    if ($@ =~ /^$ring/) { 
      redo LOOP;
    } elsif ($@) {
      die "eval error: $@";
    }
}



HTH,

--
Charles DeRykus
ced@carios2.ca.boeing.com


------------------------------

Date: 14 Feb 1997 14:10:58 -0500
From: Tom Fawcett <fawcett@nynexst.com>
Subject: Re: subtle (to me) RE problem
Message-Id: <8jd8u3kxtp.fsf@nynexst.com>

Eli the Bearded <usenet-tag@qz.little-neck.ny.us> writes:
> In a script which is scoring spam, I want to be able to
> detect N or more occurances of any one of these characters:
> 
> 	()!%*_+=|\/,<>:~-
> 
> For N=7, I have
> 
> /([\(\)!%*_+=|\\\/,<>:~-]).*${1}.*${1}.*${1}.*${1}.*${1}.*${1}/
> 
> And that gives me a "nested *?+ in regexp" error. Why?


I don't know; it works fine for me.  Remember that back-referencing
pattern elements in matches is \1 rather than $1.  I'd use this:

/([\(\)!%*_+=|\\\/,<>:~-])(.*\1){6,}/;

-Tom


------------------------------

Date: 8 Jan 97 21:33:47 GMT (Last modified)
From: Perl-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin) 
Subject: Digest Administrivia (Last modified: 8 Jan 97)
Message-Id: <null>


Administrivia:

The Perl-Users Digest is a retransmission of the USENET newsgroup
comp.lang.perl.misc.  For subscription or unsubscription requests, send
the single line:

	subscribe perl-users
or:
	unsubscribe perl-users

to almanac@ruby.oce.orst.edu.  

To submit articles to comp.lang.perl.misc (and this Digest), send your
article to perl-users@ruby.oce.orst.edu.

To submit articles to comp.lang.perl.announce, send your article to
clpa@perl.com.

To request back copies (available for a week or so), send your request
to almanac@ruby.oce.orst.edu with the command "send perl-users x.y",
where x is the volume number and y is the issue number.

The Meta-FAQ, an article containing information about the FAQ, is
available by requesting "send perl-users meta-faq". The real FAQ, as it
appeared last in the newsgroup, can be retrieved with the request "send
perl-users FAQ". Due to their sizes, neither the Meta-FAQ nor the FAQ
are included in the digest.

For other requests pertaining to the digest, send mail to
perl-users-request@ruby.oce.orst.edu. Do not waste your time or mine
sending perl questions to the -request address, I don't have time to
answer them even if I did know the answer.


------------------------------
End of Perl-Users Digest V7 Issue 952
*************************************

home help back first fref pref prev next nref lref last post