MAN page from RedHat Other perl-5.004-0.1.i386.rpm
PERLFAQ3
Section: Perl Programmers Reference Guide (1)
Updated: perl 5.004, patch 04
Index NAME
perlfaq3 - Programming Tools ($Revision: 1.22 $,
$Date: 1997/04/24 22:43:42 $)
DESCRIPTION
This section of the FAQ answers questions related to programmer toolsand programming support.
How do I do (anything)?
Have you looked at CPAN (see the perlfaq2 manpage)? The chances are thatsomeone has already written a module that can solve your problem.Have you read the appropriate man pages? Here's a brief index:
Objects perlref, perlmod, perlobj, perltie Data Structures perlref, perllol, perldsc Modules perlmod, perlmodlib, perlsub Regexps perlre, perlfunc, perlop Moving to perl5 perltrap, perl Linking w/C perlxstut, perlxs, perlcall, perlguts, perlembed Various http://www.perl.com/CPAN/doc/FMTEYEWTK/index.html (not a man-page but still useful)
the
perltoc manpage provides a crude table of contents for the perl man page set.
How can I use Perl interactively?
The typical approach uses the Perl debugger, described in theperldebug(1) man page, on an ``empty'' program, like this:
perl -de 42
Now just type in any legal Perl code, and it will be immediatelyevaluated. You can also examine the symbol table, get stackbacktraces, check variable values, set breakpoints, and otheroperations typically found in symbolic debuggers
Is there a Perl shell?
In general, no. The Shell.pm module (distributed with perl) makesperl try commands which aren't part of the Perl language as shellcommands. perlsh from the source distribution is simplistic anduninteresting, but may still be what you want.
How do I debug my Perl programs?
Have you used -w?
Have you tried use strict?
Did you check the returns of each and every system call?
Did you read the perltrap manpage?
Have you tried the Perl debugger, described in the perldebug manpage?
How do I profile my Perl programs?
You should get the Devel::DProf module from CPAN, and also useBenchmark.pm from the standard distribution. Benchmark lets you timespecific portions of your code, while Devel::DProf gives detailedbreakdowns of where your code spends its time.
How do I cross-reference my Perl programs?
The B::Xref module, shipped with the new, alpha-release Perl compiler(not the general distribution), can be used to generatecross-reference reports for Perl programs.
perl -MO=Xref[,OPTIONS] foo.pl
Is there a pretty-printer (formatter) for Perl?
There is no program that will reformat Perl as much as indent(1) willdo for C. The complex feedback between the scanner and the parser(this feedback is what confuses the vgrind and emacs programs) makes itchallenging at best to write a stand-alone Perl parser.
Of course, if you simply follow the guidelines in the perlstyle manpage, youshouldn't need to reformat.
Your editor can and should help you with source formatting. Theperl-mode for emacs can provide a remarkable amount of help with most(but not all) code, and even less programmable editors can providesignificant assistance.
If you are using to using vgrind program for printing out nice code toa laser printer, you can take a stab at this usinghttp://www.perl.com/CPAN/doc/misc/tips/working.vgrind.entry, but theresults are not particularly satisfying for sophisticated code.
Is there a ctags for Perl?
There's a simple one athttp://www.perl.com/CPAN/authors/id/TOMC/scripts/ptags.gz which may dothe trick.
Where can I get Perl macros for vi?
For a complete version of Tom Christiansen's vi configuration file,see ftp://ftp.perl.com/pub/vi/toms.exrc, the standard benchmark filefor vi emulators. This runs best with nvi, the current version of viout of Berkeley, which incidentally can be built with an embedded Perlinterpreter -- see http://www.perl.com/CPAN/src/misc .
Where can I get perl-mode for emacs?
Since Emacs version 19 patchlevel 22 or so, there have been both aperl-mode.el and support for the perl debugger built in. These shouldcome with the standard Emacs 19 distribution.
In the perl source directory, you'll find a directory called ``emacs'',which contains a cperl-mode that color-codes keywords, providescontext-sensitive help, and other nifty things.
Note that the perl-mode of emacs will have fits with ``main'foo''(single quote), and mess up the indentation and hilighting. Youshould be using ``main::foo'', anyway.
How can I use curses with Perl?
The Curses module from CPAN provides a dynamically loadable objectmodule interface to a curses library.
How can I use X or Tk with Perl?
Tk is a completely Perl-based, object-oriented interface to the Tktoolkit that doesn't force you to use Tcl just to get at Tk. Sx is aninterface to the Athena Widget set. Both are available from CPAN.
How can I generate simple menus without using CGI or Tk?
The http://www.perl.com/CPAN/authors/id/SKUNZ/perlmenu.v4.0.tar.gzmodule, which is curses-based, can help with this.
Can I dynamically load C routines into Perl?
If your system architecture supports it, then the standard perlon your system should also provide you with this via theDynaLoader module. Read the perlxstut manpage for details.
What is undump?
See the next questions.
How can I make my Perl program run faster?
The best way to do this is to come up with a better algorithm.This can often make a dramatic difference. Chapter 8 in the Camelhas some efficiency tips in it you might want to look at.
Other approaches include autoloading seldom-used Perl code. See theAutoSplit and AutoLoader modules in the standard distribution forthat. Or you could locate the bottleneck and think about writing justthat part in C, the way we used to take bottlenecks in C code andwrite them in assembler. Similar to rewriting in C is the use ofmodules that have critical sections written in C (for instance, thePDL module from CPAN).
In some cases, it may be worth it to use the backend compiler toproduce byte code (saving compilation time) or compile into C, whichwill certainly save compilation time and sometimes a small amount (butnot much) execution time. See the question about compiling your Perlprograms.
If you're currently linking your perl executable to a shared libc.so,you can often gain a 10-25% performance benefit by rebuilding it tolink with a static libc.a instead. This will make a bigger perlexecutable, but your Perl programs (and programmers) may thank you forit. See the INSTALL file in the source distribution for moreinformation.
Unsubstantiated reports allege that Perl interpreters that use sfiooutperform those that don't (for IO intensive applications). To trythis, see the INSTALL file in the source distribution, especiallythe ``Selecting File IO mechanisms'' section.
The undump program was an old attempt to speed up your Perl programby storing the already-compiled form to disk. This is no longera viable option, as it only worked on a few architectures, andwasn't a good solution anyway.
How can I make my Perl program take less memory?
When it comes to time-space tradeoffs, Perl nearly always prefers tothrow memory at a problem. Scalars in Perl use more memory thanstrings in C, arrays take more that, and hashes use even more. Whilethere's still a lot to be done, recent releases have been addressingthese issues. For example, as of 5.004, duplicate hash keys areshared amongst all hashes using them, so require no reallocation.
In some cases, using substr() or vec() to simulate arrays can behighly beneficial. For example, an array of a thousand booleans willtake at least 20,000 bytes of space, but it can be turned into one125-byte bit vector for a considerable memory savings. The standardTie::SubstrHash module can also help for certain types of datastructure. If you're working with specialist data structures(matrices, for instance) modules that implement these in C may useless memory than equivalent Perl modules.
Another thing to try is learning whether your Perl was compiled withthe system malloc or with Perl's builtin malloc. Whichever one itis, try using the other one and see whether this makes a difference.Information about malloc is in the INSTALL file in the sourcedistribution. You can find out whether you are using perl's malloc bytyping perl -V:usemymalloc.
Is it unsafe to return a pointer to local data?
No, Perl's garbage collection system takes care of this.
sub makeone { my @a = ( 1 .. 10 ); return \@a; } for $i ( 1 .. 10 ) { push @many, makeone(); } print $many[4][5], "\n";
print "@many\n";
How can I free an array or hash so my program shrinks?
You can't. Memory the system allocates to a program will never bereturned to the system. That's why long-running programs sometimesre-exec themselves.
However, judicious use of my() on your variables will help make surethat they go out of scope so that Perl can free up their storage foruse in other parts of your program. (NB: my() variables also executeabout 10% faster than globals.) A global variable, of course, nevergoes out of scope, so you can't get its space automatically reclaimed,although undef()ing and/or delete()ing it will achieve the same effect.In general, memory allocation and de-allocation isn't something you canor should be worrying about much in Perl, but even this capability(preallocation of data types) is in the works.
How can I make my CGI script more efficient?
Beyond the normal measures described to make general Perl programsfaster or smaller, a CGI program has additional issues. It may be runseveral times per second. Given that each time it runs it will needto be re-compiled and will often allocate a megabyte or more of systemmemory, this can be a killer. Compiling into C isn't going to helpyou because the process start-up overhead is where the bottleneck is.
There are at least two popular ways to avoid this overhead. Onesolution involves running the Apache HTTP server (available fromhttp://www.apache.org/) with either of the mod_perl or mod_fastcgiplugin modules. With mod_perl and the Apache::* modules (from CPAN),httpd will run with an embedded Perl interpreter which pre-compilesyour script and then executes it within the same address space withoutforking. The Apache extension also gives Perl access to the internalserver API, so modules written in Perl can do just about anything amodule written in C can. With the FCGI module (from CPAN), a Perlexecutable compiled with sfio (see the INSTALL file in thedistribution) and the mod_fastcgi module (available fromhttp://www.fastcgi.com/) each of your perl scripts becomes a permanentCGI daemon processes.
Both of these solutions can have far-reaching effects on your systemand on the way you write your CGI scripts, so investigate them withcare.
How can I hide the source for my Perl program?
Delete it. :-) Seriously, there are a number of (mostlyunsatisfactory) solutions with varying levels of ``security''.
First of all, however, you can't take away read permission, becausethe source code has to be readable in order to be compiled andinterpreted. (That doesn't mean that a CGI script's source isreadable by people on the web, though.) So you have to leave thepermissions at the socially friendly 0755 level.
Some people regard this as a security problem. If your program doesinsecure things, and relies on people not knowing how to exploit thoseinsecurities, it is not secure. It is often possible for someone todetermine the insecure things and exploit them without viewing thesource. Security through obscurity, the name for hiding your bugsinstead of fixing them, is little security indeed.
You can try using encryption via source filters (Filter::* from CPAN).But crackers might be able to decrypt it. You can try using the bytecode compiler and interpreter described below, but crackers might beable to de-compile it. You can try using the native-code compilerdescribed below, but crackers might be able to disassemble it. Thesepose varying degrees of difficulty to people wanting to get at yourcode, but none can definitively conceal it (this is true of everylanguage, not just Perl).
If you're concerned about people profiting from your code, then thebottom line is that nothing but a restrictive licence will give youlegal security. License your software and pepper it with threateningstatements like ``This is unpublished proprietary software of XYZ Corp.Your access to it does not give you permission to use it blah blahblah.'' We are not lawyers, of course, so you should see a lawyer ifyou want to be sure your licence's wording will stand up in court.
How can I compile my Perl program into byte code or C?
Malcolm Beattie has written a multifunction backend compiler,available from CPAN, that can do both these things. It is as ofFeb-1997 in late alpha release, which means it's fun to play with ifyou're a programmer but not really for people looking for turn-keysolutions.
Please understand that merely compiling into C does not in and ofitself guarantee that your code will run very much faster. That'sbecause except for lucky cases where a lot of native type inferencingis possible, the normal Perl run time system is still present and thuswill still take just as long to run and be just as big. Most programssave little more than compilation time, leaving execution no more than10-30% faster. A few rare programs actually benefit significantly(like several times faster), but this takes some tweaking of yourcode.
Malcolm will be in charge of the 5.005 release of Perl itselfto try to unify and merge his compiler and multithreading work intothe main release.
You'll probably be astonished to learn that the current version of thecompiler generates a compiled form of your script whose executable isjust as big as the original perl executable, and then some. That'sbecause as currently written, all programs are prepared for a fulleval() statement. You can tremendously reduce this cost by building ashared libperl.so library and linking against that. See theINSTALL podfile in the perl source distribution for details. Ifyou link your main perl binary with this, it will make it miniscule.For example, on one author's system, /usr/bin/perl is only 11k insize!
How can I get `#!perl' to work on [MS-DOS,NT,...]?
For OS/2 just use
extproc perl -S -your_switches
as the first line in
*.cmd file (
-S due to a bug in cmd.exe's`extproc' handling). For
DOS one should first invent a correspondingbatch file, and codify it in
ALTERNATIVE_SHEBANG (see the
INSTALL file in the source distribution for more information).
The Win95/NT installation, when using the Activeware port of Perl,will modify the Registry to associate the .pl extension with the perlinterpreter. If you install another port, or (eventually) build yourown Win95/NT Perl using WinGCC, then you'll have to modify theRegistry yourself.
Macintosh perl scripts will have the the appropriate Creator andType, so that double-clicking them will invoke the perl application.
IMPORTANT!: Whatever you do, PLEASE don't get frustrated, and justthrow the perl interpreter into your cgi-bin directory, in order toget your scripts working for a web server. This is an EXTREMELY bigsecurity risk. Take the time to figure out how to do it correctly.
Can I write useful perl programs on the command line?
Yes. Read the perlrun manpage for more information. Some examples follow.(These assume standard Unix shell quoting rules.)
# sum first and last fields perl -lane 'print $F[0] + $F[-1]'
# identify text files perl -le 'for(@ARGV) {print if -f && -T _}' * # remove comments from C program perl -0777 -pe 's{/\*.*?\*/}{}gs' foo.c # make file a month younger than today, defeating reaper daemons perl -e '$X=24*60*60; utime(time(),time() + 30 * $X,@ARGV)' *
# find first unused uid perl -le '$i++ while getpwuid($i); print $i'
# display reasonable manpath echo $PATH | perl -nl -072 -e ' s![^/+]*$!man!&&-d&&!$s{$_}++&&push@m,$_;END{print"@m"}'Ok, the last one was actually an obfuscated perl entry. :-)
Why don't perl one-liners work on my DOS/Mac/VMS system?
The problem is usually that the command interpreters on those systemshave rather different ideas about quoting than the Unix shells underwhich the one-liners were created. On some systems, you may have tochange single-quotes to double ones, which you must NOT do on Unixor Plan9 systems. You might also have to change a single % to a %%.
For example:
# Unix perl -e 'print "Hello world\n"'
# DOS, etc. perl -e "print \"Hello world\n\""
# Mac print "Hello world\n" (then Run "Myscript" or Shift-Command-R)
# VMS perl -e "print ""Hello world\n"""
The problem is that none of this is reliable: it depends on the commandinterpreter. Under Unix, the first two often work. Under
DOS, it'sentirely possible neither works. If 4DOS was the command shell, I'dprobably have better luck like this:
perl -e "print <Ctrl-x>"Hello world\n<Ctrl-x>""
Under the Mac, it depends which environment you are using. The MacPerlshell, or
MPW, is much like Unix shells in its support for severalquoting variants, except that it makes free use of the Mac's non-
ASCIIcharacters as control characters.
I'm afraid that there is no general solution to all of this. It is amess, pure and simple.
[Some of this answer was contributed by Kenneth Albanowski.]
Where can I learn about CGI or Web programming in Perl?
For modules, get the CGI or LWP modules from CPAN. For textbooks,see the two especially dedicated to web stuff in the question onbooks. For problems and questions related to the web, like ``Whydo I get 500 Errors'' or ``Why doesn't it run from the browser rightwhen it runs fine on the command line'', see these sources:
The Idiot's Guide to Solving Perl/CGI Problems, by Tom Christiansen http://www.perl.com/perl/faq/idiots-guide.html
Frequently Asked Questions about CGI Programming, by Nick Kew ftp://rtfm.mit.edu/pub/usenet/news.answers/www/cgi-faq http://www3.pair.com/webthing/docs/cgi/faqs/cgifaq.shtml
Perl/CGI programming FAQ, by Shishir Gundavaram and Tom Christiansen http://www.perl.com/perl/faq/perl-cgi-faq.html
The WWW Security FAQ, by Lincoln Stein http://www-genome.wi.mit.edu/WWW/faqs/www-security-faq.html
World Wide Web FAQ, by Thomas Boutell http://www.boutell.com/faq/
Where can I learn about object-oriented Perl programming?
the perltoot manpage is a good place to start, and you can use the perlobj manpage andthe perlbot manpage for reference. Perltoot didn't come out until the 5.004release, but you can get a copy (in pod, html, or postscript) fromhttp://www.perl.com/CPAN/doc/FMTEYEWTK/ .
Where can I learn about linking C with Perl? [h2xs, xsubpp]
If you want to call C from Perl, start with the perlxstut manpage,moving on to the perlxs manpage, the xsubpp manpage, and the perlguts manpage. If you want tocall Perl from C, then read the perlembed manpage, the perlcall manpage, andthe perlguts manpage. Don't forget that you can learn a lot from looking athow the authors of existing extension modules wrote their code andsolved their problems.
I've read perlembed, perlguts, etc., but I can't embed perl in my C program, what am I doing wrong?
Download the ExtUtils::Embed kit from CPAN and run `make test'. Ifthe tests pass, read the pods again and again and again. If theyfail, see the perlbug manpage and send a bugreport with the output ofmake test TEST_VERBOSE=1 along with perl -V.
When I tried to run my script, I got this message. What does it mean?
the perldiag manpage has a complete list of perl's error messages and warnings,with explanatory text. You can also use the splain program (distributedwith perl) to explain the error messages:
perl program 2>diag.out splain [-v] [-p] diag.out
or change your program to explain the messages for you:
use diagnostics;
or
use diagnostics -verbose;
What's MakeMaker?
This module (part of the standard perl distribution) is designed towrite a Makefile for an extension module from a Makefile.PL. For moreinformation, see the ExtUtils::MakeMaker manpage.
AUTHOR AND COPYRIGHT
Copyright (c) 1997 Tom Christiansen and Nathan Torkington.All rights reserved. See the
perlfaq manpage for distribution information.
Index
- NAME
- DESCRIPTION
- AUTHOR AND COPYRIGHT
This document was created byman2html,using the manual pages.