1N/A=head1 NAME
1N/A
1N/Aperlfaq3 - Programming Tools ($Revision: 1.37 $, $Date: 2003/11/24 19:55:50 $)
1N/A
1N/A=head1 DESCRIPTION
1N/A
1N/AThis section of the FAQ answers questions related to programmer tools
1N/Aand programming support.
1N/A
1N/A=head2 How do I do (anything)?
1N/A
1N/AHave you looked at CPAN (see L<perlfaq2>)? The chances are that
1N/Asomeone has already written a module that can solve your problem.
1N/AHave you read the appropriate manpages? Here's a brief index:
1N/A
1N/A Basics perldata, perlvar, perlsyn, perlop, perlsub
1N/A Execution perlrun, perldebug
1N/A Functions perlfunc
1N/A Objects perlref, perlmod, perlobj, perltie
1N/A Data Structures perlref, perllol, perldsc
1N/A Modules perlmod, perlmodlib, perlsub
1N/A Regexes perlre, perlfunc, perlop, perllocale
1N/A Moving to perl5 perltrap, perl
1N/A Linking w/C perlxstut, perlxs, perlcall, perlguts, perlembed
1N/A Various http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz
1N/A (not a man-page but still useful, a collection
1N/A of various essays on Perl techniques)
1N/A
1N/AA crude table of contents for the Perl manpage set is found in L<perltoc>.
1N/A
1N/A=head2 How can I use Perl interactively?
1N/A
1N/AThe typical approach uses the Perl debugger, described in the
1N/Aperldebug(1) manpage, on an ``empty'' program, like this:
1N/A
1N/A perl -de 42
1N/A
1N/ANow just type in any legal Perl code, and it will be immediately
1N/Aevaluated. You can also examine the symbol table, get stack
1N/Abacktraces, check variable values, set breakpoints, and other
1N/Aoperations typically found in symbolic debuggers.
1N/A
1N/A=head2 Is there a Perl shell?
1N/A
1N/AThe psh (Perl sh) is currently at version 1.8. The Perl Shell is a
1N/Ashell that combines the interactive nature of a Unix shell with the
1N/Apower of Perl. The goal is a full featured shell that behaves as
1N/Aexpected for normal shell activity and uses Perl syntax and
1N/Afunctionality for control-flow statements and other things.
1N/AYou can get psh at http://www.focusresearch.com/gregor/psh/ .
1N/A
1N/AZoidberg is a similar project and provides a shell written in perl,
1N/Aconfigured in perl and operated in perl. It is intended as a login shell
1N/Aand development environment. It can be found at http://zoidberg.sf.net/
1N/Aor your local CPAN mirror.
1N/A
1N/AThe Shell.pm module (distributed with Perl) makes Perl try commands
1N/Awhich aren't part of the Perl language as shell commands. perlsh
1N/Afrom the source distribution is simplistic and uninteresting, but
1N/Amay still be what you want.
1N/A
1N/A=head2 How do I find which modules are installed on my system?
1N/A
1N/AYou can use the ExtUtils::Installed module to show all
1N/Ainstalled distributions, although it can take awhile to do
1N/Aits magic. The standard library which comes with Perl just
1N/Ashows up as "Perl" (although you can get those with
1N/AModule::CoreList).
1N/A
1N/A use ExtUtils::Installed;
1N/A
1N/A my $inst = ExtUtils::Installed->new();
1N/A my @modules = $inst->modules();
1N/A
1N/AIf you want a list of all of the Perl module filenames, you
1N/Acan use File::Find::Rule.
1N/A
1N/A use File::Find::Rule;
1N/A
1N/A my @files = File::Find::Rule->file()->name( '*.pm' )->in( @INC );
1N/A
1N/AIf you do not have that module, you can do the same thing
1N/Awith File::Find which is part of the standard library.
1N/A
1N/A use File::Find;
1N/A my @files;
1N/A
1N/A find sub { push @files, $File::Find::name if -f _ && /\.pm$/ },
1N/A @INC;
1N/A
1N/A print join "\n", @files;
1N/A
1N/AIf you simply need to quickly check to see if a module is
1N/Aavailable, you can check for its documentation. If you can
1N/Aread the documentation the module is most likely installed.
1N/AIf you cannot read the documentation, the module might not
1N/Ahave any (in rare cases).
1N/A
1N/A prompt% perldoc Module::Name
1N/A
1N/AYou can also try to include the module in a one-liner to see if
1N/Aperl finds it.
1N/A
1N/A perl -MModule::Name -e1
1N/A
1N/A=head2 How do I debug my Perl programs?
1N/A
1N/AHave you tried C<use warnings> or used C<-w>? They enable warnings
1N/Ato detect dubious practices.
1N/A
1N/AHave you tried C<use strict>? It prevents you from using symbolic
1N/Areferences, makes you predeclare any subroutines that you call as bare
1N/Awords, and (probably most importantly) forces you to predeclare your
1N/Avariables with C<my>, C<our>, or C<use vars>.
1N/A
1N/ADid you check the return values of each and every system call? The operating
1N/Asystem (and thus Perl) tells you whether they worked, and if not
1N/Awhy.
1N/A
1N/A open(FH, "> /etc/cantwrite")
1N/A or die "Couldn't write to /etc/cantwrite: $!\n";
1N/A
1N/ADid you read L<perltrap>? It's full of gotchas for old and new Perl
1N/Aprogrammers and even has sections for those of you who are upgrading
1N/Afrom languages like I<awk> and I<C>.
1N/A
1N/AHave you tried the Perl debugger, described in L<perldebug>? You can
1N/Astep through your program and see what it's doing and thus work out
1N/Awhy what it's doing isn't what it should be doing.
1N/A
1N/A=head2 How do I profile my Perl programs?
1N/A
1N/AYou should get the Devel::DProf module from the standard distribution
1N/A(or separately on CPAN) and also use Benchmark.pm from the standard
1N/Adistribution. The Benchmark module lets you time specific portions of
1N/Ayour code, while Devel::DProf gives detailed breakdowns of where your
1N/Acode spends its time.
1N/A
1N/AHere's a sample use of Benchmark:
1N/A
1N/A use Benchmark;
1N/A
1N/A @junk = `cat /etc/motd`;
1N/A $count = 10_000;
1N/A
1N/A timethese($count, {
1N/A 'map' => sub { my @a = @junk;
1N/A map { s/a/b/ } @a;
1N/A return @a },
1N/A 'for' => sub { my @a = @junk;
1N/A for (@a) { s/a/b/ };
1N/A return @a },
1N/A });
1N/A
1N/AThis is what it prints (on one machine--your results will be dependent
1N/Aon your hardware, operating system, and the load on your machine):
1N/A
1N/A Benchmark: timing 10000 iterations of for, map...
1N/A for: 4 secs ( 3.97 usr 0.01 sys = 3.98 cpu)
1N/A map: 6 secs ( 4.97 usr 0.00 sys = 4.97 cpu)
1N/A
1N/ABe aware that a good benchmark is very hard to write. It only tests the
1N/Adata you give it and proves little about the differing complexities
1N/Aof contrasting algorithms.
1N/A
1N/A=head2 How do I cross-reference my Perl programs?
1N/A
1N/AThe B::Xref module can be used to generate cross-reference reports
1N/Afor Perl programs.
1N/A
1N/A perl -MO=Xref[,OPTIONS] scriptname.plx
1N/A
1N/A=head2 Is there a pretty-printer (formatter) for Perl?
1N/A
1N/APerltidy is a Perl script which indents and reformats Perl scripts
1N/Ato make them easier to read by trying to follow the rules of the
1N/AL<perlstyle>. If you write Perl scripts, or spend much time reading
1N/Athem, you will probably find it useful. It is available at
1N/Ahttp://perltidy.sourceforge.net
1N/A
1N/AOf course, if you simply follow the guidelines in L<perlstyle>,
1N/Ayou shouldn't need to reformat. The habit of formatting your code
1N/Aas you write it will help prevent bugs. Your editor can and should
1N/Ahelp you with this. The perl-mode or newer cperl-mode for emacs
1N/Acan provide remarkable amounts of help with most (but not all)
1N/Acode, and even less programmable editors can provide significant
1N/Aassistance. Tom Christiansen and many other VI users swear by
1N/Athe following settings in vi and its clones:
1N/A
1N/A set ai sw=4
1N/A map! ^O {^M}^[O^T
1N/A
1N/APut that in your F<.exrc> file (replacing the caret characters
1N/Awith control characters) and away you go. In insert mode, ^T is
1N/Afor indenting, ^D is for undenting, and ^O is for blockdenting--
1N/Aas it were. A more complete example, with comments, can be found at
1N/Ahttp://www.cpan.org/authors/id/TOMC/scripts/toms.exrc.gz
1N/A
1N/AThe a2ps http://www-inf.enst.fr/%7Edemaille/a2ps/black+white.ps.gz does
1N/Alots of things related to generating nicely printed output of
1N/Adocuments, as does enscript at http://people.ssh.fi/mtr/genscript/ .
1N/A
1N/A=head2 Is there a ctags for Perl?
1N/A
1N/ARecent versions of ctags do much more than older versions did.
1N/AEXUBERANT CTAGS is available from http://ctags.sourceforge.net/
1N/Aand does a good job of making tags files for perl code.
1N/A
1N/AThere is also a simple one at
1N/Ahttp://www.cpan.org/authors/id/TOMC/scripts/ptags.gz which may do
1N/Athe trick. It can be easy to hack this into what you want.
1N/A
1N/A=head2 Is there an IDE or Windows Perl Editor?
1N/A
1N/APerl programs are just plain text, so any editor will do.
1N/A
1N/AIf you're on Unix, you already have an IDE--Unix itself. The UNIX
1N/Aphilosophy is the philosophy of several small tools that each do one
1N/Athing and do it well. It's like a carpenter's toolbox.
1N/A
1N/AIf you want an IDE, check the following:
1N/A
1N/A=over 4
1N/A
1N/A=item Komodo
1N/A
1N/AActiveState's cross-platform (as of April 2001 Windows and Linux),
1N/Amulti-language IDE has Perl support, including a regular expression
1N/Adebugger and remote debugging
1N/A( http://www.ActiveState.com/Products/Komodo/index.html ). (Visual
1N/APerl, a Visual Studio.NET plug-in is currently (early 2001) in beta
1N/A( http://www.ActiveState.com/Products/VisualPerl/index.html )).
1N/A
1N/A=item The Object System
1N/A
1N/A( http://www.castlelink.co.uk/object_system/ ) is a Perl web
1N/Aapplications development IDE, apparently for any platform
1N/Athat runs Perl.
1N/A
1N/A=item Open Perl IDE
1N/A
1N/A( http://open-perl-ide.sourceforge.net/ )
1N/AOpen Perl IDE is an integrated development environment for writing
1N/Aand debugging Perl scripts with ActiveState's ActivePerl distribution
1N/Aunder Windows 95/98/NT/2000.
1N/A
1N/A=item PerlBuilder
1N/A
1N/A( http://www.solutionsoft.com/perl.htm ) is an integrated development
1N/Aenvironment for Windows that supports Perl development.
1N/A
1N/A=item visiPerl+
1N/A
1N/A( http://helpconsulting.net/visiperl/ )
1N/AFrom Help Consulting, for Windows.
1N/A
1N/A=item OptiPerl
1N/A
1N/A( http://www.optiperl.com/ ) is a Windows IDE with simulated CGI
1N/Aenvironment, including debugger and syntax highlighting editor.
1N/A
1N/A=back
1N/A
1N/AFor editors: if you're on Unix you probably have vi or a vi clone already,
1N/Aand possibly an emacs too, so you may not need to download anything.
1N/AIn any emacs the cperl-mode (M-x cperl-mode) gives you perhaps the
1N/Abest available Perl editing mode in any editor.
1N/A
1N/AIf you are using Windows, you can use any editor that lets
1N/Ayou work with plain text, such as NotePad or WordPad. Word
1N/Aprocessors, such as Microsoft Word or WordPerfect, typically
1N/Ado not work since they insert all sorts of behind-the-scenes
1N/Ainformation, although some allow you to save files as "Text
1N/AOnly". You can also download text editors designed
1N/Aspecifically for programming, such as Textpad
1N/A( http://www.textpad.com/ ) and UltraEdit
1N/A( http://www.ultraedit.com/ ), among others.
1N/A
1N/AIf you are using MacOS, the same concerns apply. MacPerl
1N/A(for Classic environments) comes with a simple editor.
1N/APopular external editors are BBEdit ( http://www.bbedit.com/ )
1N/Aor Alpha ( http://www.kelehers.org/alpha/ ). MacOS X users can
1N/Ause Unix editors as well.
1N/A
1N/A=over 4
1N/A
1N/A=item GNU Emacs
1N/A
1N/Ahttp://www.gnu.org/software/emacs/windows/ntemacs.html
1N/A
1N/A=item MicroEMACS
1N/A
1N/Ahttp://www.microemacs.de/
1N/A
1N/A=item XEmacs
1N/A
1N/Ahttp://www.xemacs.org/Download/index.html
1N/A
1N/A=item Jed
1N/A
1N/Ahttp://space.mit.edu/~davis/jed/
1N/A
1N/A=back
1N/A
1N/Aor a vi clone such as
1N/A
1N/A=over 4
1N/A
1N/A=item Elvis
1N/A
1N/Aftp://ftp.cs.pdx.edu/pub/elvis/ http://www.fh-wedel.de/elvis/
1N/A
1N/A=item Vile
1N/A
1N/Ahttp://dickey.his.com/vile/vile.html
1N/A
1N/A=item Vim
1N/A
1N/Ahttp://www.vim.org/
1N/A
1N/A=back
1N/A
1N/AFor vi lovers in general, Windows or elsewhere:
1N/A
1N/A http://www.thomer.com/thomer/vi/vi.html
1N/A
1N/Anvi ( http://www.bostic.com/vi/ , available from CPAN in src/misc/) is
1N/Ayet another vi clone, unfortunately not available for Windows, but in
1N/AUNIX platforms you might be interested in trying it out, firstly because
1N/Astrictly speaking it is not a vi clone, it is the real vi, or the new
1N/Aincarnation of it, and secondly because you can embed Perl inside it
1N/Ato use Perl as the scripting language. nvi is not alone in this,
1N/Athough: at least also vim and vile offer an embedded Perl.
1N/A
1N/AThe following are Win32 multilanguage editor/IDESs that support Perl:
1N/A
1N/A=over 4
1N/A
1N/A=item Codewright
1N/A
1N/Ahttp://www.starbase.com/
1N/A
1N/A=item MultiEdit
1N/A
1N/Ahttp://www.MultiEdit.com/
1N/A
1N/A=item SlickEdit
1N/A
1N/Ahttp://www.slickedit.com/
1N/A
1N/A=back
1N/A
1N/AThere is also a toyedit Text widget based editor written in Perl
1N/Athat is distributed with the Tk module on CPAN. The ptkdb
1N/A( http://world.std.com/~aep/ptkdb/ ) is a Perl/tk based debugger that
1N/Aacts as a development environment of sorts. Perl Composer
1N/A( http://perlcomposer.sourceforge.net/ ) is an IDE for Perl/Tk
1N/AGUI creation.
1N/A
1N/AIn addition to an editor/IDE you might be interested in a more
1N/Apowerful shell environment for Win32. Your options include
1N/A
1N/A=over 4
1N/A
1N/A=item Bash
1N/A
1N/Afrom the Cygwin package ( http://sources.redhat.com/cygwin/ )
1N/A
1N/A=item Ksh
1N/A
1N/Afrom the MKS Toolkit ( http://www.mks.com/ ), or the Bourne shell of
1N/Athe U/WIN environment ( http://www.research.att.com/sw/tools/uwin/ )
1N/A
1N/A=item Tcsh
1N/A
1N/Aftp://ftp.astron.com/pub/tcsh/ , see also
1N/Ahttp://www.primate.wisc.edu/software/csh-tcsh-book/
1N/A
1N/A=item Zsh
1N/A
1N/Aftp://ftp.blarg.net/users/amol/zsh/ , see also http://www.zsh.org/
1N/A
1N/A=back
1N/A
1N/AMKS and U/WIN are commercial (U/WIN is free for educational and
1N/Aresearch purposes), Cygwin is covered by the GNU Public License (but
1N/Athat shouldn't matter for Perl use). The Cygwin, MKS, and U/WIN all
1N/Acontain (in addition to the shells) a comprehensive set of standard
1N/AUNIX toolkit utilities.
1N/A
1N/AIf you're transferring text files between Unix and Windows using FTP
1N/Abe sure to transfer them in ASCII mode so the ends of lines are
1N/Aappropriately converted.
1N/A
1N/AOn Mac OS the MacPerl Application comes with a simple 32k text editor
1N/Athat behaves like a rudimentary IDE. In contrast to the MacPerl Application
1N/Athe MPW Perl tool can make use of the MPW Shell itself as an editor (with
1N/Ano 32k limit).
1N/A
1N/A=over 4
1N/A
1N/A=item BBEdit and BBEdit Lite
1N/A
1N/Aare text editors for Mac OS that have a Perl sensitivity mode
1N/A( http://web.barebones.com/ ).
1N/A
1N/A=item Alpha
1N/A
1N/Ais an editor, written and extensible in Tcl, that nonetheless has
1N/Abuilt in support for several popular markup and programming languages
1N/Aincluding Perl and HTML ( http://alpha.olm.net/ ).
1N/A
1N/A=back
1N/A
1N/APepper and Pe are programming language sensitive text editors for Mac
1N/AOS X and BeOS respectively ( http://www.hekkelman.com/ ).
1N/A
1N/A=head2 Where can I get Perl macros for vi?
1N/A
1N/AFor a complete version of Tom Christiansen's vi configuration file,
1N/Asee http://www.cpan.org/authors/Tom_Christiansen/scripts/toms.exrc.gz ,
1N/Athe standard benchmark file for vi emulators. The file runs best with nvi,
1N/Athe current version of vi out of Berkeley, which incidentally can be built
1N/Awith an embedded Perl interpreter--see http://www.cpan.org/src/misc/ .
1N/A
1N/A=head2 Where can I get perl-mode for emacs?
1N/A
1N/ASince Emacs version 19 patchlevel 22 or so, there have been both a
1N/Aperl-mode.el and support for the Perl debugger built in. These should
1N/Acome with the standard Emacs 19 distribution.
1N/A
1N/AIn the Perl source directory, you'll find a directory called "emacs",
1N/Awhich contains a cperl-mode that color-codes keywords, provides
1N/Acontext-sensitive help, and other nifty things.
1N/A
1N/ANote that the perl-mode of emacs will have fits with C<"main'foo">
1N/A(single quote), and mess up the indentation and highlighting. You
1N/Aare probably using C<"main::foo"> in new Perl code anyway, so this
1N/Ashouldn't be an issue.
1N/A
1N/A=head2 How can I use curses with Perl?
1N/A
1N/AThe Curses module from CPAN provides a dynamically loadable object
1N/Amodule interface to a curses library. A small demo can be found at the
1N/Adirectory http://www.cpan.org/authors/Tom_Christiansen/scripts/rep.gz ;
1N/Athis program repeats a command and updates the screen as needed, rendering
1N/AB<rep ps axu> similar to B<top>.
1N/A
1N/A=head2 How can I use X or Tk with Perl?
1N/A
1N/ATk is a completely Perl-based, object-oriented interface to the Tk toolkit
1N/Athat doesn't force you to use Tcl just to get at Tk. Sx is an interface
1N/Ato the Athena Widget set. Both are available from CPAN. See the
1N/Adirectory http://www.cpan.org/modules/by-category/08_User_Interfaces/
1N/A
1N/AInvaluable for Perl/Tk programming are the Perl/Tk FAQ at
1N/Ahttp://w4.lns.cornell.edu/%7Epvhp/ptk/ptkTOC.html , the Perl/Tk Reference
1N/AGuide available at
1N/Ahttp://www.cpan.org/authors/Stephen_O_Lidie/ , and the
1N/Aonline manpages at
1N/Ahttp://www-users.cs.umn.edu/%7Eamundson/perl/perltk/toc.html .
1N/A
1N/A=head2 How can I generate simple menus without using CGI or Tk?
1N/A
1N/AThe http://www.cpan.org/authors/id/SKUNZ/perlmenu.v4.0.tar.gz
1N/Amodule, which is curses-based, can help with this.
1N/A
1N/A=head2 How can I make my Perl program run faster?
1N/A
1N/AThe best way to do this is to come up with a better algorithm. This
1N/Acan often make a dramatic difference. Jon Bentley's book
1N/AI<Programming Pearls> (that's not a misspelling!) has some good tips
1N/Aon optimization, too. Advice on benchmarking boils down to: benchmark
1N/Aand profile to make sure you're optimizing the right part, look for
1N/Abetter algorithms instead of microtuning your code, and when all else
1N/Afails consider just buying faster hardware. You will probably want to
1N/Aread the answer to the earlier question ``How do I profile my Perl
1N/Aprograms?'' if you haven't done so already.
1N/A
1N/AA different approach is to autoload seldom-used Perl code. See the
1N/AAutoSplit and AutoLoader modules in the standard distribution for
1N/Athat. Or you could locate the bottleneck and think about writing just
1N/Athat part in C, the way we used to take bottlenecks in C code and
1N/Awrite them in assembler. Similar to rewriting in C, modules that have
1N/Acritical sections can be written in C (for instance, the PDL module
1N/Afrom CPAN).
1N/A
1N/AIf you're currently linking your perl executable to a shared
1N/AI<libc.so>, you can often gain a 10-25% performance benefit by
1N/Arebuilding it to link with a static libc.a instead. This will make a
1N/Abigger perl executable, but your Perl programs (and programmers) may
1N/Athank you for it. See the F<INSTALL> file in the source distribution
1N/Afor more information.
1N/A
1N/AThe undump program was an ancient attempt to speed up Perl program by
1N/Astoring the already-compiled form to disk. This is no longer a viable
1N/Aoption, as it only worked on a few architectures, and wasn't a good
1N/Asolution anyway.
1N/A
1N/A=head2 How can I make my Perl program take less memory?
1N/A
1N/AWhen it comes to time-space tradeoffs, Perl nearly always prefers to
1N/Athrow memory at a problem. Scalars in Perl use more memory than
1N/Astrings in C, arrays take more than that, and hashes use even more. While
1N/Athere's still a lot to be done, recent releases have been addressing
1N/Athese issues. For example, as of 5.004, duplicate hash keys are
1N/Ashared amongst all hashes using them, so require no reallocation.
1N/A
1N/AIn some cases, using substr() or vec() to simulate arrays can be
1N/Ahighly beneficial. For example, an array of a thousand booleans will
1N/Atake at least 20,000 bytes of space, but it can be turned into one
1N/A125-byte bit vector--a considerable memory savings. The standard
1N/ATie::SubstrHash module can also help for certain types of data
1N/Astructure. If you're working with specialist data structures
1N/A(matrices, for instance) modules that implement these in C may use
1N/Aless memory than equivalent Perl modules.
1N/A
1N/AAnother thing to try is learning whether your Perl was compiled with
1N/Athe system malloc or with Perl's builtin malloc. Whichever one it
1N/Ais, try using the other one and see whether this makes a difference.
1N/AInformation about malloc is in the F<INSTALL> file in the source
1N/Adistribution. You can find out whether you are using perl's malloc by
1N/Atyping C<perl -V:usemymalloc>.
1N/A
1N/AOf course, the best way to save memory is to not do anything to waste
1N/Ait in the first place. Good programming practices can go a long way
1N/Atoward this:
1N/A
1N/A=over 4
1N/A
1N/A=item * Don't slurp!
1N/A
1N/ADon't read an entire file into memory if you can process it line
1N/Aby line. Or more concretely, use a loop like this:
1N/A
1N/A #
1N/A # Good Idea
1N/A #
1N/A while (<FILE>) {
1N/A # ...
1N/A }
1N/A
1N/Ainstead of this:
1N/A
1N/A #
1N/A # Bad Idea
1N/A #
1N/A @data = <FILE>;
1N/A foreach (@data) {
1N/A # ...
1N/A }
1N/A
1N/AWhen the files you're processing are small, it doesn't much matter which
1N/Away you do it, but it makes a huge difference when they start getting
1N/Alarger.
1N/A
1N/A=item * Use map and grep selectively
1N/A
1N/ARemember that both map and grep expect a LIST argument, so doing this:
1N/A
1N/A @wanted = grep {/pattern/} <FILE>;
1N/A
1N/Awill cause the entire file to be slurped. For large files, it's better
1N/Ato loop:
1N/A
1N/A while (<FILE>) {
1N/A push(@wanted, $_) if /pattern/;
1N/A }
1N/A
1N/A=item * Avoid unnecessary quotes and stringification
1N/A
1N/ADon't quote large strings unless absolutely necessary:
1N/A
1N/A my $copy = "$large_string";
1N/A
1N/Amakes 2 copies of $large_string (one for $copy and another for the
1N/Aquotes), whereas
1N/A
1N/A my $copy = $large_string;
1N/A
1N/Aonly makes one copy.
1N/A
1N/ADitto for stringifying large arrays:
1N/A
1N/A {
1N/A local $, = "\n";
1N/A print @big_array;
1N/A }
1N/A
1N/Ais much more memory-efficient than either
1N/A
1N/A print join "\n", @big_array;
1N/A
1N/Aor
1N/A
1N/A {
1N/A local $" = "\n";
1N/A print "@big_array";
1N/A }
1N/A
1N/A
1N/A=item * Pass by reference
1N/A
1N/APass arrays and hashes by reference, not by value. For one thing, it's
1N/Athe only way to pass multiple lists or hashes (or both) in a single
1N/Acall/return. It also avoids creating a copy of all the contents. This
1N/Arequires some judgment, however, because any changes will be propagated
1N/Aback to the original data. If you really want to mangle (er, modify) a
1N/Acopy, you'll have to sacrifice the memory needed to make one.
1N/A
1N/A=item * Tie large variables to disk.
1N/A
1N/AFor "big" data stores (i.e. ones that exceed available memory) consider
1N/Ausing one of the DB modules to store it on disk instead of in RAM. This
1N/Awill incur a penalty in access time, but that's probably better than
1N/Acausing your hard disk to thrash due to massive swapping.
1N/A
1N/A=back
1N/A
1N/A=head2 Is it safe to return a reference to local or lexical data?
1N/A
1N/AYes. Perl's garbage collection system takes care of this so
1N/Aeverything works out right.
1N/A
1N/A sub makeone {
1N/A my @a = ( 1 .. 10 );
1N/A return \@a;
1N/A }
1N/A
1N/A for ( 1 .. 10 ) {
1N/A push @many, makeone();
1N/A }
1N/A
1N/A print $many[4][5], "\n";
1N/A
1N/A print "@many\n";
1N/A
1N/A=head2 How can I free an array or hash so my program shrinks?
1N/A
1N/AYou usually can't. On most operating systems, memory
1N/Aallocated to a program can never be returned to the system.
1N/AThat's why long-running programs sometimes re-exec
1N/Athemselves. Some operating systems (notably, systems that
1N/Ause mmap(2) for allocating large chunks of memory) can
1N/Areclaim memory that is no longer used, but on such systems,
1N/Aperl must be configured and compiled to use the OS's malloc,
1N/Anot perl's.
1N/A
1N/AHowever, judicious use of my() on your variables will help make sure
1N/Athat they go out of scope so that Perl can free up that space for
1N/Ause in other parts of your program. A global variable, of course, never
1N/Agoes out of scope, so you can't get its space automatically reclaimed,
1N/Aalthough undef()ing and/or delete()ing it will achieve the same effect.
1N/AIn general, memory allocation and de-allocation isn't something you can
1N/Aor should be worrying about much in Perl, but even this capability
1N/A(preallocation of data types) is in the works.
1N/A
1N/A=head2 How can I make my CGI script more efficient?
1N/A
1N/ABeyond the normal measures described to make general Perl programs
1N/Afaster or smaller, a CGI program has additional issues. It may be run
1N/Aseveral times per second. Given that each time it runs it will need
1N/Ato be re-compiled and will often allocate a megabyte or more of system
1N/Amemory, this can be a killer. Compiling into C B<isn't going to help
1N/Ayou> because the process start-up overhead is where the bottleneck is.
1N/A
1N/AThere are two popular ways to avoid this overhead. One solution
1N/Ainvolves running the Apache HTTP server (available from
1N/Ahttp://www.apache.org/ ) with either of the mod_perl or mod_fastcgi
1N/Aplugin modules.
1N/A
1N/AWith mod_perl and the Apache::Registry module (distributed with
1N/Amod_perl), httpd will run with an embedded Perl interpreter which
1N/Apre-compiles your script and then executes it within the same address
1N/Aspace without forking. The Apache extension also gives Perl access to
1N/Athe internal server API, so modules written in Perl can do just about
1N/Aanything a module written in C can. For more on mod_perl, see
1N/Ahttp://perl.apache.org/
1N/A
1N/AWith the FCGI module (from CPAN) and the mod_fastcgi
1N/Amodule (available from http://www.fastcgi.com/ ) each of your Perl
1N/Aprograms becomes a permanent CGI daemon process.
1N/A
1N/ABoth of these solutions can have far-reaching effects on your system
1N/Aand on the way you write your CGI programs, so investigate them with
1N/Acare.
1N/A
1N/ASee http://www.cpan.org/modules/by-category/15_World_Wide_Web_HTML_HTTP_CGI/ .
1N/A
1N/AA non-free, commercial product, ``The Velocity Engine for Perl'',
1N/A(http://www.binevolve.com/ or http://www.binevolve.com/velocigen/ )
1N/Amight also be worth looking at. It will allow you to increase the
1N/Aperformance of your Perl programs, running programs up to 25 times
1N/Afaster than normal CGI Perl when running in persistent Perl mode or 4
1N/Ato 5 times faster without any modification to your existing CGI
1N/Aprograms. Fully functional evaluation copies are available from the
1N/Aweb site.
1N/A
1N/A=head2 How can I hide the source for my Perl program?
1N/A
1N/ADelete it. :-) Seriously, there are a number of (mostly
1N/Aunsatisfactory) solutions with varying levels of ``security''.
1N/A
1N/AFirst of all, however, you I<can't> take away read permission, because
1N/Athe source code has to be readable in order to be compiled and
1N/Ainterpreted. (That doesn't mean that a CGI script's source is
1N/Areadable by people on the web, though--only by people with access to
1N/Athe filesystem.) So you have to leave the permissions at the socially
1N/Afriendly 0755 level.
1N/A
1N/ASome people regard this as a security problem. If your program does
1N/Ainsecure things and relies on people not knowing how to exploit those
1N/Ainsecurities, it is not secure. It is often possible for someone to
1N/Adetermine the insecure things and exploit them without viewing the
1N/Asource. Security through obscurity, the name for hiding your bugs
1N/Ainstead of fixing them, is little security indeed.
1N/A
1N/AYou can try using encryption via source filters (Starting from Perl
1N/A5.8 the Filter::Simple and Filter::Util::Call modules are included in
1N/Athe standard distribution), but any decent programmer will be able to
1N/Adecrypt it. You can try using the byte code compiler and interpreter
1N/Adescribed below, but the curious might still be able to de-compile it.
1N/AYou can try using the native-code compiler described below, but
1N/Acrackers might be able to disassemble it. These pose varying degrees
1N/Aof difficulty to people wanting to get at your code, but none can
1N/Adefinitively conceal it (true of every language, not just Perl).
1N/A
1N/AIt is very easy to recover the source of Perl programs. You simply
1N/Afeed the program to the perl interpreter and use the modules in
1N/Athe B:: hierarchy. The B::Deparse module should be able to
1N/Adefeat most attempts to hide source. Again, this is not
1N/Aunique to Perl.
1N/A
1N/AIf you're concerned about people profiting from your code, then the
1N/Abottom line is that nothing but a restrictive license will give you
1N/Alegal security. License your software and pepper it with threatening
1N/Astatements like ``This is unpublished proprietary software of XYZ Corp.
1N/AYour access to it does not give you permission to use it blah blah
1N/Ablah.'' We are not lawyers, of course, so you should see a lawyer if
1N/Ayou want to be sure your license's wording will stand up in court.
1N/A
1N/A=head2 How can I compile my Perl program into byte code or C?
1N/A
1N/AMalcolm Beattie has written a multifunction backend compiler,
1N/Aavailable from CPAN, that can do both these things. It is included
1N/Ain the perl5.005 release, but is still considered experimental.
1N/AThis means it's fun to play with if you're a programmer but not
1N/Areally for people looking for turn-key solutions.
1N/A
1N/AMerely compiling into C does not in and of itself guarantee that your
1N/Acode will run very much faster. That's because except for lucky cases
1N/Awhere a lot of native type inferencing is possible, the normal Perl
1N/Arun-time system is still present and so your program will take just as
1N/Along to run and be just as big. Most programs save little more than
1N/Acompilation time, leaving execution no more than 10-30% faster. A few
1N/Arare programs actually benefit significantly (even running several times
1N/Afaster), but this takes some tweaking of your code.
1N/A
1N/AYou'll probably be astonished to learn that the current version of the
1N/Acompiler generates a compiled form of your script whose executable is
1N/Ajust as big as the original perl executable, and then some. That's
1N/Abecause as currently written, all programs are prepared for a full
1N/Aeval() statement. You can tremendously reduce this cost by building a
1N/Ashared I<libperl.so> library and linking against that. See the
1N/AF<INSTALL> podfile in the Perl source distribution for details. If
1N/Ayou link your main perl binary with this, it will make it minuscule.
1N/AFor example, on one author's system, F</usr/bin/perl> is only 11k in
1N/Asize!
1N/A
1N/AIn general, the compiler will do nothing to make a Perl program smaller,
1N/Afaster, more portable, or more secure. In fact, it can make your
1N/Asituation worse. The executable will be bigger, your VM system may take
1N/Alonger to load the whole thing, the binary is fragile and hard to fix,
1N/Aand compilation never stopped software piracy in the form of crackers,
1N/Aviruses, or bootleggers. The real advantage of the compiler is merely
1N/Apackaging, and once you see the size of what it makes (well, unless
1N/Ayou use a shared I<libperl.so>), you'll probably want a complete
1N/APerl install anyway.
1N/A
1N/A=head2 How can I compile Perl into Java?
1N/A
1N/AYou can also integrate Java and Perl with the
1N/APerl Resource Kit from O'Reilly and Associates. See
1N/Ahttp://www.oreilly.com/catalog/prkunix/ .
1N/A
1N/APerl 5.6 comes with Java Perl Lingo, or JPL. JPL, still in
1N/Adevelopment, allows Perl code to be called from Java. See jpl/README
1N/Ain the Perl source tree.
1N/A
1N/A=head2 How can I get C<#!perl> to work on [MS-DOS,NT,...]?
1N/A
1N/AFor OS/2 just use
1N/A
1N/A extproc perl -S -your_switches
1N/A
1N/Aas the first line in C<*.cmd> file (C<-S> due to a bug in cmd.exe's
1N/A`extproc' handling). For DOS one should first invent a corresponding
1N/Abatch file and codify it in C<ALTERNATE_SHEBANG> (see the
1N/AF<dosish.h> file in the source distribution for more information).
1N/A
1N/AThe Win95/NT installation, when using the ActiveState port of Perl,
1N/Awill modify the Registry to associate the C<.pl> extension with the
1N/Aperl interpreter. If you install another port, perhaps even building
1N/Ayour own Win95/NT Perl from the standard sources by using a Windows port
1N/Aof gcc (e.g., with cygwin or mingw32), then you'll have to modify
1N/Athe Registry yourself. In addition to associating C<.pl> with the
1N/Ainterpreter, NT people can use: C<SET PATHEXT=%PATHEXT%;.PL> to let them
1N/Arun the program C<install-linux.pl> merely by typing C<install-linux>.
1N/A
1N/AMacintosh Perl programs will have the appropriate Creator and
1N/AType, so that double-clicking them will invoke the Perl application.
1N/A
1N/AI<IMPORTANT!>: Whatever you do, PLEASE don't get frustrated, and just
1N/Athrow the perl interpreter into your cgi-bin directory, in order to
1N/Aget your programs working for a web server. This is an EXTREMELY big
1N/Asecurity risk. Take the time to figure out how to do it correctly.
1N/A
1N/A=head2 Can I write useful Perl programs on the command line?
1N/A
1N/AYes. Read L<perlrun> for more information. Some examples follow.
1N/A(These assume standard Unix shell quoting rules.)
1N/A
1N/A # sum first and last fields
1N/A perl -lane 'print $F[0] + $F[-1]' *
1N/A
1N/A # identify text files
1N/A perl -le 'for(@ARGV) {print if -f && -T _}' *
1N/A
1N/A # remove (most) comments from C program
1N/A perl -0777 -pe 's{/\*.*?\*/}{}gs' foo.c
1N/A
1N/A # make file a month younger than today, defeating reaper daemons
1N/A perl -e '$X=24*60*60; utime(time(),time() + 30 * $X,@ARGV)' *
1N/A
1N/A # find first unused uid
1N/A perl -le '$i++ while getpwuid($i); print $i'
1N/A
1N/A # display reasonable manpath
1N/A echo $PATH | perl -nl -072 -e '
1N/A s![^/+]*$!man!&&-d&&!$s{$_}++&&push@m,$_;END{print"@m"}'
1N/A
1N/AOK, the last one was actually an Obfuscated Perl Contest entry. :-)
1N/A
1N/A=head2 Why don't Perl one-liners work on my DOS/Mac/VMS system?
1N/A
1N/AThe problem is usually that the command interpreters on those systems
1N/Ahave rather different ideas about quoting than the Unix shells under
1N/Awhich the one-liners were created. On some systems, you may have to
1N/Achange single-quotes to double ones, which you must I<NOT> do on Unix
1N/Aor Plan9 systems. You might also have to change a single % to a %%.
1N/A
1N/AFor example:
1N/A
1N/A # Unix
1N/A perl -e 'print "Hello world\n"'
1N/A
1N/A # DOS, etc.
1N/A perl -e "print \"Hello world\n\""
1N/A
1N/A # Mac
1N/A print "Hello world\n"
1N/A (then Run "Myscript" or Shift-Command-R)
1N/A
1N/A # MPW
1N/A perl -e 'print "Hello world\n"'
1N/A
1N/A # VMS
1N/A perl -e "print ""Hello world\n"""
1N/A
1N/AThe problem is that none of these examples are reliable: they depend on the
1N/Acommand interpreter. Under Unix, the first two often work. Under DOS,
1N/Ait's entirely possible that neither works. If 4DOS was the command shell,
1N/Ayou'd probably have better luck like this:
1N/A
1N/A perl -e "print <Ctrl-x>"Hello world\n<Ctrl-x>""
1N/A
1N/AUnder the Mac, it depends which environment you are using. The MacPerl
1N/Ashell, or MPW, is much like Unix shells in its support for several
1N/Aquoting variants, except that it makes free use of the Mac's non-ASCII
1N/Acharacters as control characters.
1N/A
1N/AUsing qq(), q(), and qx(), instead of "double quotes", 'single
1N/Aquotes', and `backticks`, may make one-liners easier to write.
1N/A
1N/AThere is no general solution to all of this. It is a mess.
1N/A
1N/A[Some of this answer was contributed by Kenneth Albanowski.]
1N/A
1N/A=head2 Where can I learn about CGI or Web programming in Perl?
1N/A
1N/AFor modules, get the CGI or LWP modules from CPAN. For textbooks,
1N/Asee the two especially dedicated to web stuff in the question on
1N/Abooks. For problems and questions related to the web, like ``Why
1N/Ado I get 500 Errors'' or ``Why doesn't it run from the browser right
1N/Awhen it runs fine on the command line'', see the troubleshooting
1N/Aguides and references in L<perlfaq9> or in the CGI MetaFAQ:
1N/A
1N/A http://www.perl.org/CGI_MetaFAQ.html
1N/A
1N/A=head2 Where can I learn about object-oriented Perl programming?
1N/A
1N/AA good place to start is L<perltoot>, and you can use L<perlobj>,
1N/AL<perlboot>, L<perltoot>, L<perltooc>, and L<perlbot> for reference.
1N/A(If you are using really old Perl, you may not have all of these,
1N/Atry http://www.perldoc.com/ , but consider upgrading your perl.)
1N/A
1N/AA good book on OO on Perl is the "Object-Oriented Perl"
1N/Aby Damian Conway from Manning Publications,
1N/Ahttp://www.manning.com/Conway/index.html
1N/A
1N/A=head2 Where can I learn about linking C with Perl? [h2xs, xsubpp]
1N/A
1N/AIf you want to call C from Perl, start with L<perlxstut>,
1N/Amoving on to L<perlxs>, L<xsubpp>, and L<perlguts>. If you want to
1N/Acall Perl from C, then read L<perlembed>, L<perlcall>, and
1N/AL<perlguts>. Don't forget that you can learn a lot from looking at
1N/Ahow the authors of existing extension modules wrote their code and
1N/Asolved their problems.
1N/A
1N/A=head2 I've read perlembed, perlguts, etc., but I can't embed perl in
1N/Amy C program; what am I doing wrong?
1N/A
1N/ADownload the ExtUtils::Embed kit from CPAN and run `make test'. If
1N/Athe tests pass, read the pods again and again and again. If they
1N/Afail, see L<perlbug> and send a bug report with the output of
1N/AC<make test TEST_VERBOSE=1> along with C<perl -V>.
1N/A
1N/A=head2 When I tried to run my script, I got this message. What does it mean?
1N/A
1N/AA complete list of Perl's error messages and warnings with explanatory
1N/Atext can be found in L<perldiag>. You can also use the splain program
1N/A(distributed with Perl) to explain the error messages:
1N/A
1N/A perl program 2>diag.out
1N/A splain [-v] [-p] diag.out
1N/A
1N/Aor change your program to explain the messages for you:
1N/A
1N/A use diagnostics;
1N/A
1N/Aor
1N/A
1N/A use diagnostics -verbose;
1N/A
1N/A=head2 What's MakeMaker?
1N/A
1N/AThis module (part of the standard Perl distribution) is designed to
1N/Awrite a Makefile for an extension module from a Makefile.PL. For more
1N/Ainformation, see L<ExtUtils::MakeMaker>.
1N/A
1N/A=head1 AUTHOR AND COPYRIGHT
1N/A
1N/ACopyright (c) 1997-2002 Tom Christiansen and Nathan Torkington.
1N/AAll rights reserved.
1N/A
1N/AThis documentation is free; you can redistribute it and/or modify it
1N/Aunder the same terms as Perl itself.
1N/A
1N/AIrrespective of its distribution, all code examples here are in the public
1N/Adomain. You are permitted and encouraged to use this code and any
1N/Aderivatives thereof in your own programs for fun or for profit as you
1N/Asee fit. A simple comment in the code giving credit to the FAQ would
1N/Abe courteous but is not required.