From: spp@vx.com
Newsgroups: comp.lang.perl,comp.answers,news.answers
Subject: comp.lang.perl FAQ 3/5 - Programming Aids
Followup-To: poster
Date: 15 Nov 1994 10:09:26 GMT
Organization: none
Lines: 424
Approved: news-answers-request@MIT.EDU
Message-ID: <perl-faq/part3_784894001@rtfm.mit.edu>
References: <perl-faq/part0_784894001@rtfm.mit.edu>
X-Last-Updated: 1994/11/14
Originator: faqserv@bloom-picayune.MIT.EDU

Archive-name: perl-faq/part3
Version: $Id: part3,v 2.1 1994/10/25 13:56:19 spp Exp spp $
Posting-Frequency: bi-weekly

This posting contains answers to general information questions, mostly
about programming aids.  


3.1) How can I use Perl interactively?
    
    The easiest way to do this is to run Perl under its debugger.  If you
    have no program to debug, you can invoke the debugger on an `empty'
    program like this: 

    	perl -de 0

    (The more positive hackers prefer "perl -de 1". :-)

    Now you can type in any legal Perl code, and it will be immediately
    evaluated.  You can also examine the symbol table, get stack
    backtraces, check variable values, and if you want to, set breakpoints
    and do the other things you can do in a symbolic debugger. 


3.2) Is there a Perl profiler?

    While there isn't one included with the perl source distribution (yet) 
    various folks have written packages that allow you to do at least some 
    sort of profiling.  The strategy usually includes modifying the perl 
    debugger to handle profiling.  Authors of these packages include 

	Wayne Thompson 		<me@anywhere.EBay.Sun.COM>
	Ray Lischner 		<lisch@sysserver1.mentor.com>
	Kresten Krab Thorup 	<krab@iesd.auc.dk>  

    The original articles by these folks containing their profilers are
    available on convex.com in /pub/perl/information/profiling.shar via
    anon ftp. 


3.3) Is there a yacc for Perl?

    Yes!! It's a version of Berkeley yacc that outputs Perl code instead
    of C code!  You can get this from ftp.sterling.com [192.124.9.1] in
    /local/perl-byacc1.8.1.tar.Z, or send the author mail for details.


3.4) Is there a pretty-printer for Perl?

    That depends on what you mean.  If you want something that works like
    vgrind on Perl programs, then the answer is "yes, nearly".  Here's a
    vgrind entry for perl: 

	PERL|perl|Perl:\
	    :pb=^\d?(sub|package)\d\p\d:\
	    :bb={:be=}:cb=#:ce=$:sb=":se=\e":lb=':\
	    :le=\e':tl:\
	    :id=_:\
	    :kw=\
	    if for foreach unless until while continue else elsif \
	    do eval require \
	    die exit \
	    defined delete reset \
	    goto last redo next dump \
	    local undef return  \
	    write format  \
	    sub package

    It doesn't actually do everything right; in particular, 
    things like $#, $', s#/foo##, and $foo'bar all confuse it.

    David Levine uses this:

    # perl 4.x                    David Levine <levine@ics.uci.edu> 05 apr 1993
    # Derived from Tom Christiansen's perl vgrindef.  I'd like to treat all  of
    # perl's built-ins as  keywords,  but vgrind   fields are  limited  to 1024
    # characters  and the built-ins overflow that (surprise  :-).  So, I didn't
    # include the dbm*, end*, get*, msg*, sem*, set*,  and  shm* functions.   I
    # couldn't come up with an easy way to  distinguish beginnings  of literals
    # ('...') from package prefixes, so literals are not marked.
    # Be sure to:
    # 1) include whitespace between a subprogram name and its opening {
    # 2) include whitespace before a comment (so that $# doesn't get
    # interpreted as one).
    perl4:\
	    :pb=^\d?(sub|package)\d\p\d:\
	    :id=$%@_:\
	    :bb=\e{:be=\e}:cb=\d\e#:ce=$:sb=\e":se=\e":\
	    :kw=accept alarm atan2 bind binmode caller chdir chmod chop \
    chown chroot close closedir connect continue cos crypt defined delete \
    die do dump each else elsif eof eval exec exit exp fcntl fileno flock \
    for foreach fork format getc gmtime goto grep hex if include index int \
    ioctl join keys kill last length link listen local localtime log lstat \
    m mkdir next oct open opendir ord pack package pipe pop print printf \
    push q qq qx rand read readdir readlink recv redo rename require reset \
    return reverse rewinddir rindex rmdir s scalar seek seekdir select send \
    shift shutdown sin sleep socket socketpair sort splice split sprintf \
    sqrt srand stat study sub substr symlink syscall sysread system \
    syswrite tell telldir time times tr truncate umask undef unless unlink \
    unpack unshift until utime values vec wait waitpid wantarray warn while \
    write y: 

    If what you mean is whether there is a program that will reformat the
    program much as indent(1) will do for C, then the answer is no.  The
    complex feedback between the scanner and the parser (as in the things
    that confuse vgrind) make it challenging at best to write a stand-alone
    Perl parser. 


3.5) There's an a2p and an s2p; why isn't there a p2c (perl-to-C)?

    Because the Pascal people would be upset that we stole their name. :-)

    The dynamic nature of Perl's do and eval operators (and remember that
    constructs like s/$mac_donald/$mac_gregor/eieio count as an eval) would
    make this very difficult.  To fully support them, you would have to put
    the whole Perl interpreter into each compiled version for those scripts
    using them.  This is what undump does right now, if your machine has it.
    If what you're doing will be faster in C than in Perl, maybe it should
    have been written in C in the first place.  For things that ought to be
    written in Perl, the interpreter will be just about as fast, because the
    pattern matching routines won't work any faster linked into a C program.
    Even in the case of simple Perl programs that don't do any fancy evals, the
    major gain would be in compiling the control flow tests, with the rest
    still being a maze of twisty, turny subroutine calls.  Since these are not
    usually the major bottleneck in the program, there's not as much to be
    gained via compilation as one might think.

    However, we're still looking for someone to generate byte-compiled
    code for Perl, or eventually even C code out of it.  These are
    probably masters and PhD thesis topics respectively, and no one
    has begun work on it yet.



3.6) Where can I get a perl-mode for emacs?

    Since Emacs version 19 patchlevel 22 or so, there has been both a
    perl-mode.el and support for the perl debugger built in.  These should
    come with the standard Emacs 19 distribution.

    In the perl source directory, you'll find a directory called
    "emacs", which contains several files that should help you.


3.7) Is there a Perl shell? 
    
    Not really.  Perl is a programming language, not a command
    interpreter.  There is a very simple one called "perlsh"
    included in the Perl source distribution.  It just does this:

	$/ = '';        # set paragraph mode
	$SHlinesep = "\n";
	while ($SHcmd = <>) {
	    $/ = $SHlinesep;
	    eval $SHcmd; print $@ || "\n";
	    $SHlinesep = $/; $/ = '';
	}

    Not very interesting, eh?  

    Daniel Smith <dansmith@autodesk.com> is working on an interactive Perl
    shell called SoftList.  It's currently at version 3.0beta.  SoftList
    3.0 has tcsh-like command line editing, can let you define a file of
    aliases so that you can run chunks of perl or UNIX commands, and so
    on.  You can send mail to him for further information and availability.

3.8) How can I use curses with perl?

    In release 4 of perl, the only way to do this was was to build a
    curseperl binary by linking in your C curses library as described in
    the usub subdirectory of the perl sources.  This requires a modicum of
    work, but it will be reasonably fast since it's all in C (assuming you
    consider curses reasonably fast. :-) Programs written using this
    method require the modified curseperl, not vanilla perl, to run.
    While this is something of a disadvantage, experience indicates that
    it's better to use curseperl than to try to roll your own using
    termcap directly.

    Fortunately, in version 5, Curses is a dynamically loaded extension
    by William Setzer*.  You should be able to pick it up wherever you
    get Perl 5 from, or at least these places:

	ftp://ftp.ncsu.edu/pub/math/wsetzer/cursperl5a6.tar.gz
        ftp://ftp.metronet.com/pub/perlinfo/perl5/cursperl5a6.tar.gz
        ftp://ftp.cs.ruu.nl/pub/PERL/perl5.0/cursperl5a6.tar.gz

    For a good example of using (v4) curseperl, you might want to pick up a
    copy of  Steven L Kunz's* "perl menus" package ("menu.pl") via
    anonymous FTP from "ftp.iastate.edu".  It's in the /pub/perl as

	menu.pl.v2.3.shr1
	menu.pl.v2.3.shr2
	menu.pl.v2.3.tar.Z

    menus.pl is a complete menu front-end for curseperl and demonstates
    a lot of things (plus it is useful to boot if you want full-screen
    menu selection ability).

    Another possibility is to use Henk Penning's cterm package, a curses
    emulation library written in perl.  cterm is actually a separate
    program with which you communicate via a pipe.  It is available from
    ftp.cs.ruu.nl [131.211.80.17] via anonymous ftp. in the directory
    pub/PERL.  You may also acquire the package via email in compressed,
    uuencoded form by sending a message to mail-server@cs.ruu.nl
    containing these lines:

	begin
	send PERL/cterm.shar.Z
	end

    See the question on retrieving perl via mail for more information on
    how to retrieve other items of interest from the mail server
    there.


3.9) How can I use X with Perl?

    Right now, you have several choices.  If you are still using perl4, use
    the WAFE or STDWIN packages, or try to make your own usub binding.

    However, if you've upgraded to version 5, you have several exciting
    possibilities, with more popping up each day.  Right now, Tk and Sx
    are the best known such extensions.

    If you like the tk package, you should get the Tk extension kit,
    written by Malcolm Beattie*.  Here are some places to get it:

     Tk (as in tcl/tk, but sans tcl)

	ftp://ftp.cis.ufl.edu/pub/perl/src/tkperl/tkperl5a4.tar.gz
        ftp://ftp.khoros.unm.edu/pub/perl/extensions/tkperl5a4.tar.gz
        ftp://ftp.metronet.com/pub/perlinfo/perl5/tkperl/tkperl5a4.tar.gz
        ftp://ftp.cs.ruu.nl/pub/PERL/perl5.0/tkperl5a4.tar.gz
        ftp://black.ox.ac.uk/src/ALPHA/tkperl5a4.tar.gz
 
        (try 5a5 everywhere after 2pm UST Thu 20 Oct 1994, as in)
 
        ftp://sable.ox.ac.uk/pub/perl/tkperl5a5.tar.gz
 
    You may also use the old Sx package, (Athena & Xlib), written by
    originally written by by Dominic Giampaolo*, then and rewritten for Sx
    by Frederic Chauveau*.fr>.  It's available from these sites:

        ftp://ftp.pasteur.fr/pub/Perl/Sx.tar.gz
        ftp://ftp.khoros.unm.edu/pub/perl/extensions/Sx.tar.gz
        ftp://ftp.metronet.com/pub/perlinfo/perl5/Sx.tar.gz
        ftp://ftp.cs.ruu.nl/pub/PERL/perl5.0/PerlDoc.ps.gz
 
    STDWIN is a library written by Guido van Rossum* (author of the Python
    programming language) that is portable between Mac, Dos and X11.  One
    could write a Perl agent to speak to this STDWIN server.

    WAFE is a package that implements a symbolic interface to the Athena
    widgets (X11R5). A typical Wafe application consists in our framework
    of two parts: the front-end (we call it Wafe for Widget[Athena]front
    end) and an application program running typically as a separate
    process.  The application program can be implemented in an arbitrary
    programming language and talks to the front-end via stdio.  Since Wafe
    (the front-end) was developed using the extensible TCL shell (cite John
    Ousterhout), an application program can dynamically submit requests to
    the front-end to build up the graphical user interface; the
    application can even down-load application specific procedures into
    the front-end.  The distribution contains sample application programs
    in Perl, GAWK, Prolog, TCL, and C talking to the same Wafe binary.
    Many of the demo applications are implemented in Perl.  Wafe 0.9 can
    be obtained via anonymous ftp from 
	ftp.wu-wien.ac.at[137.208.3.5]:pub/src/X11/wafe-0.9.tar.Z

    Alternatively, you could use wish from tcl. 

    #!/usr/local/bin/perl
    #####################################################################
    #  An example of calling wish as a subshell under Perl and
    #  interactively communicating with it through sockets.
    #
    #  The script is directly based on Gustaf Neumann's perlwafe script.
    #
    #  Dov Grobgeld dov@menora.weizmann.ac.il
    #  1993-05-17
    #####################################################################

    $wishbin = "/usr/local/bin/wish";

    die "socketpair unsuccessful: $!!\n" unless socketpair(W0,WISH,1,1,0);
    if ($pid=fork) {
	    select(WISH); $| = 1;
	    select(STDOUT);

	# Create some TCL procedures
	    print WISH 'proc echo {s} {puts stdout $s; flush stdout}',"\n";

	# Create the widgets
	print WISH <<TCL;
	# This is a comment "inside" wish

	frame .f -relief raised -border 1 -bg green
	pack append . .f {top fill expand}

	button .f.button-pressme -text "Press me" -command {
	    echo "That's nice."
	}
	button .f.button-quit -text quit -command {
	    echo "quit"
	}
	pack append .f .f.button-pressme {top fill expand} \\
		       .f.button-quit {top expand}

TCL
	;
	# Here is the main loop which receives and sends commands
	# to wish.
	while (<WISH>) {
	    chop;
	    print "Wish sais: <$_>\n";
	    if (/^quit/) { print WISH "destroy .\n"; last; }
	}
	    wait;
    } elsif (defined $pid) {
	open(STDOUT, ">&W0");
	open(STDIN, ">&W0");
	close(W0);
	select(STDOUT); $| = 1;
	exec "$wishbin --";
    } else {
	die "fork error: $!\n";
    }


3.10) Can I dynamically load C user routines?

    Yes -- dynamic loading comes with the distribution.  That means that
    you no longer need 18 different versions of fooperl floating around.
    In fact, all of perl can be stuck into a libperl.so library and
    then your /usr/local/bin/perl binary reduced to just 50k or so.
    See DynLoader(3pm) for details.

    In perl4, the answer is kinda.  One package has been released that does
    this, by Roberto Salama*.  He writes:

    Here is a version of dylperl, dynamic linker for perl. The code here is
    based on Oliver Sharp's May 1993 article in Dr. Dobbs Journal (Dynamic
    Linking under Berkeley UNIX). 

	      dyl.h 
	      dyl.c - code extracted from Oliver Sharp's article

	      hash.h
	      hash.c - Berkeley's hash functions, should use perl's but
		       could not be bothered

	   dylperl.c - perl usersubs
	      user.c - userinit function

	    sample.c - sample code to be dyl'ed
	   sample2.c -          "
	     test.pl - sample perl script that dyl's sample*.o

    The Makefile assumes that uperl.o is in /usr/local/src/perl/... You
    will probable have to change this to reflect your installation. Other
    than that, just type 'make'...

    The idea behind being able to dynamically link code into perl is that
    the linked code should become perl functions, i.e. they can be invoked
    as &foo(...).  For this to happen, the incrementally loaded code must
    use the perl stack, look at sample.c to get a better idea.

    The few functions that make up this package are outlined below.

    &dyl("file.o"): dynamically link file.o. All functions and non-static
		   variables become visible from within perl. This
		   function returns a pointer to an internal hash table
		   corresponding to the symbol table of the newly loaded
		   code.

		   eg: $ht = &dyl("sample.o")

	   This function can also be called with the -L and -l ld options.

		   eg: $ht = &dyl(""sample2.o", "-L/usr/lib", "-lm")
		       will also pick up the math library if sample.o
		       accesses any symbols there.

    &dyl_find("func"): find symbol 'func' and return its symbol table entry

    &dyl_functions($ht): print the contents of the internal hash table
    &dyl_print_symbols($f): prints the contents of the symbol returned by
    dyl_find() 

    There is very little documentation, maybe something to do for a future
    release.  The files sample.o, and sample2.o contain code to be
    incrementally loaded, test.pl is the test perl script.

    Comments are welcome. I submit this code for public consumption and,
    basically, am not responsible for it in any way.


3.11) What is undump and where can I get it?

    The undump program comes from the TeX distribution.  If you have TeX,
    then you may have a working undump.  If you don't, and you can't get
    one, *AND* you have a GNU emacs working on your machine that can clone
    itself, then you might try taking its unexec() function and compiling
    Perl with -DUNEXEC, which will make Perl call unexec() instead of
    abort().  You'll have to add unexec.o to the objects line in the
    Makefile.  If you succeed, post to comp.lang.perl about your experience
    so others can benefit from it. 

    If you have a version of undump that works with Perl, please submit
    its anon-FTP whereabouts to the FAQ maintainer.


3.12) How can I get '#!perl' to work under MS-DOS?

    John Dallman* has written a program "#!perl.exe" which will do this.
    It is available through anonymous ftp from ftp.ee.umanitoba.ca in the
    directory /pub/msdos/perl/hbp_20.zip.  This program works by finding
    the script and perl.exe, building a command line and running perl.exe
    as a child process.  For more information on this, contact John
    directly.
Stephen P Potter		spp@vx.com		Varimetrix Corporation
2350 Commerce Park Drive, Suite 4			    Palm Bay, FL 32905
(407) 676-3222 						  CAD/CAM/CAE/Software
