1PERLFAQ3(1)            Perl Programmers Reference Guide            PERLFAQ3(1)
2
3
4

NAME

6       perlfaq3 - Programming Tools
7

DESCRIPTION

9       This section of the FAQ answers questions related to programmer tools
10       and programming support.
11
12   How do I do (anything)?
13       Have you looked at CPAN (see perlfaq2)?  The chances are that someone
14       has already written a module that can solve your problem.  Have you
15       read the appropriate manpages?  Here's a brief index:
16
17               Basics          perldata, perlvar, perlsyn, perlop, perlsub
18               Execution       perlrun, perldebug
19               Functions       perlfunc
20               Objects         perlref, perlmod, perlobj, perltie
21               Data Structures perlref, perllol, perldsc
22               Modules         perlmod, perlmodlib, perlsub
23               Regexes         perlre, perlfunc, perlop, perllocale
24               Moving to perl5 perltrap, perl
25               Linking w/C     perlxstut, perlxs, perlcall, perlguts, perlembed
26               Various         http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz
27                               (not a man-page but still useful, a collection
28                                of various essays on Perl techniques)
29
30       A crude table of contents for the Perl manpage set is found in perltoc.
31
32   How can I use Perl interactively?
33       The typical approach uses the Perl debugger, described in the
34       perldebug(1) manpage, on an "empty" program, like this:
35
36           perl -de 42
37
38       Now just type in any legal Perl code, and it will be immediately
39       evaluated.  You can also examine the symbol table, get stack
40       backtraces, check variable values, set breakpoints, and other
41       operations typically found in symbolic debuggers.
42
43   Is there a Perl shell?
44       The "psh" (Perl sh) is currently at version 1.8. The Perl Shell is a
45       shell that combines the interactive nature of a Unix shell with the
46       power of Perl. The goal is a full featured shell that behaves as
47       expected for normal shell activity and uses Perl syntax and
48       functionality for control-flow statements and other things. You can get
49       "psh" at http://sourceforge.net/projects/psh/ .
50
51       "Zoidberg" is a similar project and provides a shell written in perl,
52       configured in perl and operated in perl. It is intended as a login
53       shell and development environment. It can be found at
54       http://pardus-larus.student.utwente.nl/~pardus/projects/zoidberg/ or
55       your local CPAN mirror.
56
57       The "Shell.pm" module (distributed with Perl) makes Perl try commands
58       which aren't part of the Perl language as shell commands.  "perlsh"
59       from the source distribution is simplistic and uninteresting, but may
60       still be what you want.
61
62   How do I find which modules are installed on my system?
63       From the command line, you can use the "cpan" command's "-l" switch:
64
65               $ cpan -l
66
67       You can also use "cpan"'s "-a" switch to create an autobundle file that
68       "CPAN.pm" understands and can use to re-install every module:
69
70               $ cpan -a
71
72       Inside a Perl program, you can use the "ExtUtils::Installed" module to
73       show all installed distributions, although it can take awhile to do its
74       magic.  The standard library which comes with Perl just shows up as
75       "Perl" (although you can get those with "Module::CoreList").
76
77               use ExtUtils::Installed;
78
79               my $inst    = ExtUtils::Installed->new();
80               my @modules = $inst->modules();
81
82       If you want a list of all of the Perl module filenames, you can use
83       "File::Find::Rule":
84
85               use File::Find::Rule;
86
87               my @files = File::Find::Rule->
88                       extras({follow => 1})->
89                       file()->
90                       name( '*.pm' )->
91                       in( @INC )
92                       ;
93
94       If you do not have that module, you can do the same thing with
95       "File::Find" which is part of the standard library:
96
97               use File::Find;
98               my @files;
99
100               find(
101                   {
102                       wanted => sub {
103                           push @files, $File::Find::fullname
104                               if -f $File::Find::fullname && /\.pm$/
105                       },
106                       follow => 1,
107                       follow_skip => 2,
108                   },
109                   @INC
110               );
111
112               print join "\n", @files;
113
114       If you simply need to quickly check to see if a module is available,
115       you can check for its documentation.  If you can read the documentation
116       the module is most likely installed.  If you cannot read the
117       documentation, the module might not have any (in rare cases):
118
119               $ perldoc Module::Name
120
121       You can also try to include the module in a one-liner to see if perl
122       finds it:
123
124               $ perl -MModule::Name -e1
125
126   How do I debug my Perl programs?
127       (contributed by brian d foy)
128
129       Before you do anything else, you can help yourself by ensuring that you
130       let Perl tell you about problem areas in your code. By turning on
131       warnings and strictures, you can head off many problems before they get
132       too big. You can find out more about these in strict and warnings.
133
134               #!/usr/bin/perl
135               use strict;
136               use warnings;
137
138       Beyond that, the simplest debugger is the "print" function. Use it to
139       look at values as you run your program:
140
141               print STDERR "The value is [$value]\n";
142
143       The "Data::Dumper" module can pretty-print Perl data structures:
144
145               use Data::Dumper qw( Dumper );
146               print STDERR "The hash is " . Dumper( \%hash ) . "\n";
147
148       Perl comes with an interactive debugger, which you can start with the
149       "-d" switch. It's fully explained in perldebug.
150
151       If you'd like a graphical user interface and you have "Tk", you can use
152       "ptkdb". It's on CPAN and available for free.
153
154       If you need something much more sophisticated and controllable, Leon
155       Brocard's "Devel::ebug" (which you can call with the "-D" switch as
156       "-Debug") gives you the programmatic hooks into everything you need to
157       write your own (without too much pain and suffering).
158
159       You can also use a commercial debugger such as Affrus (Mac OS X),
160       Komodo from Activestate (Windows and Mac OS X), or EPIC (most
161       platforms).
162
163   How do I profile my Perl programs?
164       (contributed by brian d foy, updated Fri Jul 25 12:22:26 PDT 2008)
165
166       The "Devel" namespace has several modules which you can use to profile
167       your Perl programs. The "Devel::DProf" module comes with Perl and you
168       can invoke it with the "-d" switch:
169
170               perl -d:DProf program.pl
171
172       After running your program under "DProf", you'll get a tmon.out file
173       with the profile data. To look at the data, you can turn it into a
174       human-readable report with the "dprofpp" program that comes with
175       "Devel::DProf".
176
177               dprofpp
178
179       You can also do the profiling and reporting in one step with the "-p"
180       switch to "dprofpp":
181
182               dprofpp -p program.pl
183
184       The "Devel::NYTProf" (New York Times Profiler) does both statement and
185       subroutine profiling. It's available from CPAN and you also invoke it
186       with the "-d" switch:
187
188               perl -d:NYTProf some_perl.pl
189
190       Like "DProf", it creates a database of the profile information that you
191       can turn into reports. The "nytprofhtml" command turns the data into an
192       HTML report similar to the "Devel::Cover" report:
193
194               nytprofhtml
195
196       CPAN has several other profilers that you can invoke in the same
197       fashion. You might also be interested in using the "Benchmark" to
198       measure and compare code snippets.
199
200       You can read more about profiling in Programming Perl, chapter 20, or
201       Mastering Perl, chapter 5.
202
203       perldebguts documents creating a custom debugger if you need to create
204       a special sort of profiler. brian d foy describes the process in The
205       Perl Journal, "Creating a Perl Debugger", http://www.ddj.com/184404522
206       , and "Profiling in Perl" http://www.ddj.com/184404580 .
207
208       Perl.com has two interesting articles on profiling: "Profiling Perl",
209       by Simon Cozens, http://www.perl.com/lpt/a/850 and "Debugging and
210       Profiling mod_perl Applications", by Frank Wiles,
211       http://www.perl.com/pub/a/2006/02/09/debug_mod_perl.html .
212
213       Randal L. Schwartz writes about profiling in "Speeding up Your Perl
214       Programs" for Unix Review,
215       http://www.stonehenge.com/merlyn/UnixReview/col49.html , and "Profiling
216       in Template Toolkit via Overriding" for Linux Magazine,
217       http://www.stonehenge.com/merlyn/LinuxMag/col75.html .
218
219   How do I cross-reference my Perl programs?
220       The "B::Xref" module can be used to generate cross-reference reports
221       for Perl programs.
222
223           perl -MO=Xref[,OPTIONS] scriptname.plx
224
225   Is there a pretty-printer (formatter) for Perl?
226       "Perltidy" is a Perl script which indents and reformats Perl scripts to
227       make them easier to read by trying to follow the rules of the
228       perlstyle. If you write Perl scripts, or spend much time reading them,
229       you will probably find it useful.  It is available at
230       http://perltidy.sourceforge.net .
231
232       Of course, if you simply follow the guidelines in perlstyle, you
233       shouldn't need to reformat.  The habit of formatting your code as you
234       write it will help prevent bugs.  Your editor can and should help you
235       with this.  The perl-mode or newer cperl-mode for emacs can provide
236       remarkable amounts of help with most (but not all) code, and even less
237       programmable editors can provide significant assistance.  Tom
238       Christiansen and many other VI users  swear by the following settings
239       in vi and its clones:
240
241           set ai sw=4
242           map! ^O {^M}^[O^T
243
244       Put that in your .exrc file (replacing the caret characters with
245       control characters) and away you go.  In insert mode, ^T is for
246       indenting, ^D is for undenting, and ^O is for blockdenting--as it were.
247       A more complete example, with comments, can be found at
248       http://www.cpan.org/authors/id/TOMC/scripts/toms.exrc.gz
249
250       The a2ps http://www-inf.enst.fr/%7Edemaille/a2ps/black+white.ps.gz does
251       lots of things related to generating nicely printed output of
252       documents.
253
254   Is there a ctags for Perl?
255       (contributed by brian d foy)
256
257       Ctags uses an index to quickly find things in source code, and many
258       popular editors support ctags for several different languages,
259       including Perl.
260
261       Exuberent ctags supports Perl: http://ctags.sourceforge.net/
262
263       You might also try pltags: http://www.mscha.com/pltags.zip
264
265   Is there an IDE or Windows Perl Editor?
266       Perl programs are just plain text, so any editor will do.
267
268       If you're on Unix, you already have an IDE--Unix itself.  The Unix
269       philosophy is the philosophy of several small tools that each do one
270       thing and do it well.  It's like a carpenter's toolbox.
271
272       If you want an IDE, check the following (in alphabetical order, not
273       order of preference):
274
275       Eclipse
276           http://e-p-i-c.sf.net/
277
278           The Eclipse Perl Integration Project integrates Perl
279           editing/debugging with Eclipse.
280
281       Enginsite
282           http://www.enginsite.com/
283
284           Perl Editor by EngInSite is a complete integrated development
285           environment (IDE) for creating, testing, and  debugging  Perl
286           scripts; the tool runs on Windows 9x/NT/2000/XP or later.
287
288       Komodo
289           http://www.ActiveState.com/Products/Komodo/
290
291           ActiveState's cross-platform (as of October 2004, that's Windows,
292           Linux, and Solaris), multi-language IDE has Perl support, including
293           a regular expression debugger and remote debugging.
294
295       Notepad++
296           http://notepad-plus.sourceforge.net/
297
298       Open Perl IDE
299           http://open-perl-ide.sourceforge.net/
300
301           Open Perl IDE is an integrated development environment for writing
302           and debugging Perl scripts with ActiveState's ActivePerl
303           distribution under Windows 95/98/NT/2000.
304
305       OptiPerl
306           http://www.optiperl.com/
307
308           OptiPerl is a Windows IDE with simulated CGI environment, including
309           debugger and syntax highlighting editor.
310
311       Padre
312           http://padre.perlide.org/
313
314           Padre is cross-platform IDE for Perl written in Perl using
315           wxWidgets to provide a native look and feel. It's open source under
316           the Artistic License.
317
318       PerlBuilder
319           http://www.solutionsoft.com/perl.htm
320
321           PerlBuilder is an integrated development environment for Windows
322           that supports Perl development.
323
324       visiPerl+
325           http://helpconsulting.net/visiperl/
326
327           From Help Consulting, for Windows.
328
329       Visual Perl
330           http://www.activestate.com/Products/Visual_Perl/
331
332           Visual Perl is a Visual Studio.NET plug-in from ActiveState.
333
334       Zeus
335           http://www.zeusedit.com/lookmain.html
336
337           Zeus for Window is another Win32 multi-language editor/IDE that
338           comes with support for Perl:
339
340       For editors: if you're on Unix you probably have vi or a vi clone
341       already, and possibly an emacs too, so you may not need to download
342       anything. In any emacs the cperl-mode (M-x cperl-mode) gives you
343       perhaps the best available Perl editing mode in any editor.
344
345       If you are using Windows, you can use any editor that lets you work
346       with plain text, such as NotePad or WordPad. Word processors, such as
347       Microsoft Word or WordPerfect, typically do not work since they insert
348       all sorts of behind-the-scenes information, although some allow you to
349       save files as "Text Only". You can also download text editors designed
350       specifically for programming, such as Textpad ( http://www.textpad.com/
351       ) and UltraEdit ( http://www.ultraedit.com/ ), among others.
352
353       If you are using MacOS, the same concerns apply. MacPerl (for Classic
354       environments) comes with a simple editor. Popular external editors are
355       BBEdit ( http://www.bbedit.com/ ) or Alpha (
356       http://www.his.com/~jguyer/Alpha/Alpha8.html ). MacOS X users can use
357       Unix editors as well.
358
359       GNU Emacs
360           http://www.gnu.org/software/emacs/windows/ntemacs.html
361
362       MicroEMACS
363           http://www.microemacs.de/
364
365       XEmacs
366           http://www.xemacs.org/Download/index.html
367
368       Jed http://space.mit.edu/~davis/jed/
369
370       or a vi clone such as
371
372       Elvis
373           ftp://ftp.cs.pdx.edu/pub/elvis/ http://www.fh-wedel.de/elvis/
374
375       Vile
376           http://dickey.his.com/vile/vile.html
377
378       Vim http://www.vim.org/
379
380       For vi lovers in general, Windows or elsewhere:
381
382               http://www.thomer.com/thomer/vi/vi.html
383
384       nvi ( http://www.bostic.com/vi/ , available from CPAN in src/misc/) is
385       yet another vi clone, unfortunately not available for Windows, but in
386       Unix platforms you might be interested in trying it out, firstly
387       because strictly speaking it is not a vi clone, it is the real vi, or
388       the new incarnation of it, and secondly because you can embed Perl
389       inside it to use Perl as the scripting language.  nvi is not alone in
390       this, though: at least also vim and vile offer an embedded Perl.
391
392       The following are Win32 multilanguage editor/IDEs that support Perl:
393
394       Codewright
395           http://www.borland.com/codewright/
396
397       MultiEdit
398           http://www.MultiEdit.com/
399
400       SlickEdit
401           http://www.slickedit.com/
402
403       ConTEXT
404           http://www.contexteditor.org/
405
406       There is also a toyedit Text widget based editor written in Perl that
407       is distributed with the Tk module on CPAN.  The ptkdb (
408       http://ptkdb.sourceforge.net/ ) is a Perl/tk based debugger that acts
409       as a development environment of sorts.  Perl Composer (
410       http://perlcomposer.sourceforge.net/ ) is an IDE for Perl/Tk GUI
411       creation.
412
413       In addition to an editor/IDE you might be interested in a more powerful
414       shell environment for Win32.  Your options include
415
416       Bash
417           from the Cygwin package ( http://sources.redhat.com/cygwin/ )
418
419       Ksh from the MKS Toolkit ( http://www.mkssoftware.com/ ), or the Bourne
420           shell of the U/WIN environment (
421           http://www.research.att.com/sw/tools/uwin/ )
422
423       Tcsh
424           ftp://ftp.astron.com/pub/tcsh/ , see also
425           http://www.primate.wisc.edu/software/csh-tcsh-book/
426
427       Zsh http://www.zsh.org/
428
429       MKS and U/WIN are commercial (U/WIN is free for educational and
430       research purposes), Cygwin is covered by the GNU General Public License
431       (but that shouldn't matter for Perl use).  The Cygwin, MKS, and U/WIN
432       all contain (in addition to the shells) a comprehensive set of standard
433       Unix toolkit utilities.
434
435       If you're transferring text files between Unix and Windows using FTP be
436       sure to transfer them in ASCII mode so the ends of lines are
437       appropriately converted.
438
439       On Mac OS the MacPerl Application comes with a simple 32k text editor
440       that behaves like a rudimentary IDE.  In contrast to the MacPerl
441       Application the MPW Perl tool can make use of the MPW Shell itself as
442       an editor (with no 32k limit).
443
444       Affrus
445           is a full Perl development environment with full debugger support (
446           http://www.latenightsw.com ).
447
448       Alpha
449           is an editor, written and extensible in Tcl, that nonetheless has
450           built in support for several popular markup and programming
451           languages including Perl and HTML (
452           http://www.his.com/~jguyer/Alpha/Alpha8.html ).
453
454       BBEdit and BBEdit Lite
455           are text editors for Mac OS that have a Perl sensitivity mode (
456           http://web.barebones.com/ ).
457
458   Where can I get Perl macros for vi?
459       For a complete version of Tom Christiansen's vi configuration file, see
460       http://www.cpan.org/authors/Tom_Christiansen/scripts/toms.exrc.gz , the
461       standard benchmark file for vi emulators.  The file runs best with nvi,
462       the current version of vi out of Berkeley, which incidentally can be
463       built with an embedded Perl interpreter--see
464       http://www.cpan.org/src/misc/ .
465
466   Where can I get perl-mode or cperl-mode for emacs?
467       Since Emacs version 19 patchlevel 22 or so, there have been both a
468       perl-mode.el and support for the Perl debugger built in.  These should
469       come with the standard Emacs 19 distribution.
470
471       Note that the perl-mode of emacs will have fits with "main'foo" (single
472       quote), and mess up the indentation and highlighting.  You are probably
473       using "main::foo" in new Perl code anyway, so this shouldn't be an
474       issue.
475
476       For CPerlMode, see http://www.emacswiki.org/cgi-bin/wiki/CPerlMode
477
478   How can I use curses with Perl?
479       The Curses module from CPAN provides a dynamically loadable object
480       module interface to a curses library.  A small demo can be found at the
481       directory http://www.cpan.org/authors/Tom_Christiansen/scripts/rep.gz ;
482       this program repeats a command and updates the screen as needed,
483       rendering rep ps axu similar to top.
484
485   How can I write a GUI (X, Tk, Gtk, etc.) in Perl?
486       (contributed by Ben Morrow)
487
488       There are a number of modules which let you write GUIs in Perl. Most
489       GUI toolkits have a perl interface: an incomplete list follows.
490
491       Tk  This works under Unix and Windows, and the current version doesn't
492           look half as bad under Windows as it used to. Some of the gui
493           elements still don't 'feel' quite right, though. The interface is
494           very natural and 'perlish', making it easy to use in small scripts
495           that just need a simple gui. It hasn't been updated in a while.
496
497       Wx  This is a Perl binding for the cross-platform wxWidgets toolkit (
498           http://www.wxwidgets.org ). It works under Unix, Win32 and Mac OS
499           X, using native widgets (Gtk under Unix). The interface follows the
500           C++ interface closely, but the documentation is a little sparse for
501           someone who doesn't know the library, mostly just referring you to
502           the C++ documentation.
503
504       Gtk and Gtk2
505           These are Perl bindings for the Gtk toolkit ( http://www.gtk.org ).
506           The interface changed significantly between versions 1 and 2 so
507           they have separate Perl modules. It runs under Unix, Win32 and Mac
508           OS X (currently it requires an X server on Mac OS, but a 'native'
509           port is underway), and the widgets look the same on every plaform:
510           i.e., they don't match the native widgets. As with Wx, the Perl
511           bindings follow the C API closely, and the documentation requires
512           you to read the C documentation to understand it.
513
514       Win32::GUI
515           This provides access to most of the Win32 GUI widgets from Perl.
516           Obviously, it only runs under Win32, and uses native widgets. The
517           Perl interface doesn't really follow the C interface: it's been
518           made more Perlish, and the documentation is pretty good. More
519           advanced stuff may require familiarity with the C Win32 APIs, or
520           reference to MSDN.
521
522       CamelBones
523           CamelBones ( http://camelbones.sourceforge.net ) is a Perl
524           interface to Mac OS X's Cocoa GUI toolkit, and as such can be used
525           to produce native GUIs on Mac OS X. It's not on CPAN, as it
526           requires frameworks that CPAN.pm doesn't know how to install, but
527           installation is via the standard OSX package installer. The Perl
528           API is, again, very close to the ObjC API it's wrapping, and the
529           documentation just tells you how to translate from one to the
530           other.
531
532       Qt  There is a Perl interface to TrollTech's Qt toolkit, but it does
533           not appear to be maintained.
534
535       Athena
536           Sx is an interface to the Athena widget set which comes with X, but
537           again it appears not to be much used nowadays.
538
539   How can I make my Perl program run faster?
540       The best way to do this is to come up with a better algorithm.  This
541       can often make a dramatic difference.  Jon Bentley's book Programming
542       Pearls (that's not a misspelling!)  has some good tips on optimization,
543       too.  Advice on benchmarking boils down to: benchmark and profile to
544       make sure you're optimizing the right part, look for better algorithms
545       instead of microtuning your code, and when all else fails consider just
546       buying faster hardware.  You will probably want to read the answer to
547       the earlier question "How do I profile my Perl programs?" if you
548       haven't done so already.
549
550       A different approach is to autoload seldom-used Perl code.  See the
551       AutoSplit and AutoLoader modules in the standard distribution for that.
552       Or you could locate the bottleneck and think about writing just that
553       part in C, the way we used to take bottlenecks in C code and write them
554       in assembler.  Similar to rewriting in C, modules that have critical
555       sections can be written in C (for instance, the PDL module from CPAN).
556
557       If you're currently linking your perl executable to a shared libc.so,
558       you can often gain a 10-25% performance benefit by rebuilding it to
559       link with a static libc.a instead.  This will make a bigger perl
560       executable, but your Perl programs (and programmers) may thank you for
561       it.  See the INSTALL file in the source distribution for more
562       information.
563
564       The undump program was an ancient attempt to speed up Perl program by
565       storing the already-compiled form to disk.  This is no longer a viable
566       option, as it only worked on a few architectures, and wasn't a good
567       solution anyway.
568
569   How can I make my Perl program take less memory?
570       When it comes to time-space tradeoffs, Perl nearly always prefers to
571       throw memory at a problem.  Scalars in Perl use more memory than
572       strings in C, arrays take more than that, and hashes use even more.
573       While there's still a lot to be done, recent releases have been
574       addressing these issues.  For example, as of 5.004, duplicate hash keys
575       are shared amongst all hashes using them, so require no reallocation.
576
577       In some cases, using substr() or vec() to simulate arrays can be highly
578       beneficial.  For example, an array of a thousand booleans will take at
579       least 20,000 bytes of space, but it can be turned into one 125-byte bit
580       vector--a considerable memory savings.  The standard Tie::SubstrHash
581       module can also help for certain types of data structure.  If you're
582       working with specialist data structures (matrices, for instance)
583       modules that implement these in C may use less memory than equivalent
584       Perl modules.
585
586       Another thing to try is learning whether your Perl was compiled with
587       the system malloc or with Perl's builtin malloc.  Whichever one it is,
588       try using the other one and see whether this makes a difference.
589       Information about malloc is in the INSTALL file in the source
590       distribution.  You can find out whether you are using perl's malloc by
591       typing "perl -V:usemymalloc".
592
593       Of course, the best way to save memory is to not do anything to waste
594       it in the first place. Good programming practices can go a long way
595       toward this:
596
597       ·   Don't slurp!
598
599           Don't read an entire file into memory if you can process it line by
600           line. Or more concretely, use a loop like this:
601
602                   #
603                   # Good Idea
604                   #
605                   while (<FILE>) {
606                      # ...
607                   }
608
609           instead of this:
610
611                   #
612                   # Bad Idea
613                   #
614                   @data = <FILE>;
615                   foreach (@data) {
616                       # ...
617                   }
618
619           When the files you're processing are small, it doesn't much matter
620           which way you do it, but it makes a huge difference when they start
621           getting larger.
622
623       ·   Use map and grep selectively
624
625           Remember that both map and grep expect a LIST argument, so doing
626           this:
627
628                   @wanted = grep {/pattern/} <FILE>;
629
630           will cause the entire file to be slurped. For large files, it's
631           better to loop:
632
633                   while (<FILE>) {
634                           push(@wanted, $_) if /pattern/;
635                   }
636
637       ·   Avoid unnecessary quotes and stringification
638
639           Don't quote large strings unless absolutely necessary:
640
641                   my $copy = "$large_string";
642
643           makes 2 copies of $large_string (one for $copy and another for the
644           quotes), whereas
645
646                   my $copy = $large_string;
647
648           only makes one copy.
649
650           Ditto for stringifying large arrays:
651
652                   {
653                   local $, = "\n";
654                   print @big_array;
655                   }
656
657           is much more memory-efficient than either
658
659                   print join "\n", @big_array;
660
661           or
662
663                   {
664                   local $" = "\n";
665                   print "@big_array";
666                   }
667
668       ·   Pass by reference
669
670           Pass arrays and hashes by reference, not by value. For one thing,
671           it's the only way to pass multiple lists or hashes (or both) in a
672           single call/return. It also avoids creating a copy of all the
673           contents. This requires some judgement, however, because any
674           changes will be propagated back to the original data. If you really
675           want to mangle (er, modify) a copy, you'll have to sacrifice the
676           memory needed to make one.
677
678       ·   Tie large variables to disk.
679
680           For "big" data stores (i.e. ones that exceed available memory)
681           consider using one of the DB modules to store it on disk instead of
682           in RAM. This will incur a penalty in access time, but that's
683           probably better than causing your hard disk to thrash due to
684           massive swapping.
685
686   Is it safe to return a reference to local or lexical data?
687       Yes. Perl's garbage collection system takes care of this so everything
688       works out right.
689
690           sub makeone {
691               my @a = ( 1 .. 10 );
692               return \@a;
693           }
694
695           for ( 1 .. 10 ) {
696               push @many, makeone();
697           }
698
699           print $many[4][5], "\n";
700
701           print "@many\n";
702
703   How can I free an array or hash so my program shrinks?
704       (contributed by Michael Carman)
705
706       You usually can't. Memory allocated to lexicals (i.e. my() variables)
707       cannot be reclaimed or reused even if they go out of scope. It is
708       reserved in case the variables come back into scope. Memory allocated
709       to global variables can be reused (within your program) by using
710       undef() and/or delete().
711
712       On most operating systems, memory allocated to a program can never be
713       returned to the system. That's why long-running programs sometimes re-
714       exec themselves. Some operating systems (notably, systems that use
715       mmap(2) for allocating large chunks of memory) can reclaim memory that
716       is no longer used, but on such systems, perl must be configured and
717       compiled to use the OS's malloc, not perl's.
718
719       In general, memory allocation and de-allocation isn't something you can
720       or should be worrying about much in Perl.
721
722       See also "How can I make my Perl program take less memory?"
723
724   How can I make my CGI script more efficient?
725       Beyond the normal measures described to make general Perl programs
726       faster or smaller, a CGI program has additional issues.  It may be run
727       several times per second.  Given that each time it runs it will need to
728       be re-compiled and will often allocate a megabyte or more of system
729       memory, this can be a killer.  Compiling into C isn't going to help you
730       because the process start-up overhead is where the bottleneck is.
731
732       There are two popular ways to avoid this overhead.  One solution
733       involves running the Apache HTTP server (available from
734       http://www.apache.org/ ) with either of the mod_perl or mod_fastcgi
735       plugin modules.
736
737       With mod_perl and the Apache::Registry module (distributed with
738       mod_perl), httpd will run with an embedded Perl interpreter which pre-
739       compiles your script and then executes it within the same address space
740       without forking.  The Apache extension also gives Perl access to the
741       internal server API, so modules written in Perl can do just about
742       anything a module written in C can.  For more on mod_perl, see
743       http://perl.apache.org/
744
745       With the FCGI module (from CPAN) and the mod_fastcgi module (available
746       from http://www.fastcgi.com/ ) each of your Perl programs becomes a
747       permanent CGI daemon process.
748
749       Both of these solutions can have far-reaching effects on your system
750       and on the way you write your CGI programs, so investigate them with
751       care.
752
753       See
754       http://www.cpan.org/modules/by-category/15_World_Wide_Web_HTML_HTTP_CGI/
755       .
756
757   How can I hide the source for my Perl program?
758       Delete it. :-) Seriously, there are a number of (mostly unsatisfactory)
759       solutions with varying levels of "security".
760
761       First of all, however, you can't take away read permission, because the
762       source code has to be readable in order to be compiled and interpreted.
763       (That doesn't mean that a CGI script's source is readable by people on
764       the web, though--only by people with access to the filesystem.)  So you
765       have to leave the permissions at the socially friendly 0755 level.
766
767       Some people regard this as a security problem.  If your program does
768       insecure things and relies on people not knowing how to exploit those
769       insecurities, it is not secure.  It is often possible for someone to
770       determine the insecure things and exploit them without viewing the
771       source.  Security through obscurity, the name for hiding your bugs
772       instead of fixing them, is little security indeed.
773
774       You can try using encryption via source filters (Starting from Perl 5.8
775       the Filter::Simple and Filter::Util::Call modules are included in the
776       standard distribution), but any decent programmer will be able to
777       decrypt it.  You can try using the byte code compiler and interpreter
778       described later in perlfaq3, but the curious might still be able to de-
779       compile it. You can try using the native-code compiler described later,
780       but crackers might be able to disassemble it.  These pose varying
781       degrees of difficulty to people wanting to get at your code, but none
782       can definitively conceal it (true of every language, not just Perl).
783
784       It is very easy to recover the source of Perl programs.  You simply
785       feed the program to the perl interpreter and use the modules in the B::
786       hierarchy.  The B::Deparse module should be able to defeat most
787       attempts to hide source.  Again, this is not unique to Perl.
788
789       If you're concerned about people profiting from your code, then the
790       bottom line is that nothing but a restrictive license will give you
791       legal security.  License your software and pepper it with threatening
792       statements like "This is unpublished proprietary software of XYZ Corp.
793       Your access to it does not give you permission to use it blah blah
794       blah."  We are not lawyers, of course, so you should see a lawyer if
795       you want to be sure your license's wording will stand up in court.
796
797   How can I compile my Perl program into byte code or C?
798       (contributed by brian d foy)
799
800       In general, you can't do this.  There are some things that may work for
801       your situation though.  People usually ask this question because they
802       want to distribute their works without giving away the source code, and
803       most solutions trade disk space for convenience.  You probably won't
804       see much of a speed increase either, since most solutions simply bundle
805       a Perl interpreter in the final product (but see "How can I make my
806       Perl program run faster?").
807
808       The Perl Archive Toolkit ( http://par.perl.org/ ) is Perl's analog to
809       Java's JAR.  It's freely available and on CPAN (
810       http://search.cpan.org/dist/PAR/ ).
811
812       There are also some commercial products that may work for you, although
813       you have to buy a license for them.
814
815       The Perl Dev Kit ( http://www.activestate.com/Products/Perl_Dev_Kit/ )
816       from ActiveState can "Turn your Perl programs into ready-to-run
817       executables for HP-UX, Linux, Solaris and Windows."
818
819       Perl2Exe ( http://www.indigostar.com/perl2exe.htm ) is a command line
820       program for converting perl scripts to executable files.  It targets
821       both Windows and Unix platforms.
822
823   How can I get "#!perl" to work on [MS-DOS,NT,...]?
824       For OS/2 just use
825
826           extproc perl -S -your_switches
827
828       as the first line in "*.cmd" file ("-S" due to a bug in cmd.exe's
829       "extproc" handling).  For DOS one should first invent a corresponding
830       batch file and codify it in "ALTERNATE_SHEBANG" (see the dosish.h file
831       in the source distribution for more information).
832
833       The Win95/NT installation, when using the ActiveState port of Perl,
834       will modify the Registry to associate the ".pl" extension with the perl
835       interpreter.  If you install another port, perhaps even building your
836       own Win95/NT Perl from the standard sources by using a Windows port of
837       gcc (e.g., with cygwin or mingw32), then you'll have to modify the
838       Registry yourself.  In addition to associating ".pl" with the
839       interpreter, NT people can use: "SET PATHEXT=%PATHEXT%;.PL" to let them
840       run the program "install-linux.pl" merely by typing "install-linux".
841
842       Under "Classic" MacOS, a perl program will have the appropriate Creator
843       and Type, so that double-clicking them will invoke the MacPerl
844       application.  Under Mac OS X, clickable apps can be made from any "#!"
845       script using Wil Sanchez' DropScript utility:
846       http://www.wsanchez.net/software/ .
847
848       IMPORTANT!: Whatever you do, PLEASE don't get frustrated, and just
849       throw the perl interpreter into your cgi-bin directory, in order to get
850       your programs working for a web server.  This is an EXTREMELY big
851       security risk.  Take the time to figure out how to do it correctly.
852
853   Can I write useful Perl programs on the command line?
854       Yes.  Read perlrun for more information.  Some examples follow.  (These
855       assume standard Unix shell quoting rules.)
856
857           # sum first and last fields
858           perl -lane 'print $F[0] + $F[-1]' *
859
860           # identify text files
861           perl -le 'for(@ARGV) {print if -f && -T _}' *
862
863           # remove (most) comments from C program
864           perl -0777 -pe 's{/\*.*?\*/}{}gs' foo.c
865
866           # make file a month younger than today, defeating reaper daemons
867           perl -e '$X=24*60*60; utime(time(),time() + 30 * $X,@ARGV)' *
868
869           # find first unused uid
870           perl -le '$i++ while getpwuid($i); print $i'
871
872           # display reasonable manpath
873           echo $PATH | perl -nl -072 -e '
874               s![^/+]*$!man!&&-d&&!$s{$_}++&&push@m,$_;END{print"@m"}'
875
876       OK, the last one was actually an Obfuscated Perl Contest entry. :-)
877
878   Why don't Perl one-liners work on my DOS/Mac/VMS system?
879       The problem is usually that the command interpreters on those systems
880       have rather different ideas about quoting than the Unix shells under
881       which the one-liners were created.  On some systems, you may have to
882       change single-quotes to double ones, which you must NOT do on Unix or
883       Plan9 systems.  You might also have to change a single % to a %%.
884
885       For example:
886
887           # Unix (including Mac OS X)
888           perl -e 'print "Hello world\n"'
889
890           # DOS, etc.
891           perl -e "print \"Hello world\n\""
892
893           # Mac Classic
894           print "Hello world\n"
895            (then Run "Myscript" or Shift-Command-R)
896
897           # MPW
898           perl -e 'print "Hello world\n"'
899
900           # VMS
901           perl -e "print ""Hello world\n"""
902
903       The problem is that none of these examples are reliable: they depend on
904       the command interpreter.  Under Unix, the first two often work. Under
905       DOS, it's entirely possible that neither works.  If 4DOS was the
906       command shell, you'd probably have better luck like this:
907
908         perl -e "print <Ctrl-x>"Hello world\n<Ctrl-x>""
909
910       Under the Mac, it depends which environment you are using.  The MacPerl
911       shell, or MPW, is much like Unix shells in its support for several
912       quoting variants, except that it makes free use of the Mac's non-ASCII
913       characters as control characters.
914
915       Using qq(), q(), and qx(), instead of "double quotes", 'single quotes',
916       and `backticks`, may make one-liners easier to write.
917
918       There is no general solution to all of this.  It is a mess.
919
920       [Some of this answer was contributed by Kenneth Albanowski.]
921
922   Where can I learn about CGI or Web programming in Perl?
923       For modules, get the CGI or LWP modules from CPAN.  For textbooks, see
924       the two especially dedicated to web stuff in the question on books.
925       For problems and questions related to the web, like "Why do I get 500
926       Errors" or "Why doesn't it run from the browser right when it runs fine
927       on the command line", see the troubleshooting guides and references in
928       perlfaq9 or in the CGI MetaFAQ:
929
930               http://www.perl.org/CGI_MetaFAQ.html
931
932   Where can I learn about object-oriented Perl programming?
933       A good place to start is perltoot, and you can use perlobj, perlboot,
934       perltoot, perltooc, and perlbot for reference.
935
936       A good book on OO on Perl is the "Object-Oriented Perl" by Damian
937       Conway from Manning Publications, or "Intermediate Perl" by Randal
938       Schwartz, brian d foy, and Tom Phoenix from O'Reilly Media.
939
940   Where can I learn about linking C with Perl?
941       If you want to call C from Perl, start with perlxstut, moving on to
942       perlxs, xsubpp, and perlguts.  If you want to call Perl from C, then
943       read perlembed, perlcall, and perlguts.  Don't forget that you can
944       learn a lot from looking at how the authors of existing extension
945       modules wrote their code and solved their problems.
946
947       You might not need all the power of XS. The Inline::C module lets you
948       put C code directly in your Perl source. It handles all the magic to
949       make it work. You still have to learn at least some of the perl API but
950       you won't have to deal with the complexity of the XS support files.
951
952   I've read perlembed, perlguts, etc., but I can't embed perl in my C
953       program; what am I doing wrong?
954       Download the ExtUtils::Embed kit from CPAN and run `make test'.  If the
955       tests pass, read the pods again and again and again.  If they fail, see
956       perlbug and send a bug report with the output of "make test
957       TEST_VERBOSE=1" along with "perl -V".
958
959   When I tried to run my script, I got this message. What does it mean?
960       A complete list of Perl's error messages and warnings with explanatory
961       text can be found in perldiag. You can also use the splain program
962       (distributed with Perl) to explain the error messages:
963
964           perl program 2>diag.out
965           splain [-v] [-p] diag.out
966
967       or change your program to explain the messages for you:
968
969           use diagnostics;
970
971       or
972
973           use diagnostics -verbose;
974
975   What's MakeMaker?
976       (contributed by brian d foy)
977
978       The "ExtUtils::MakeMaker" module, better known simply as "MakeMaker",
979       turns a Perl script, typically called "Makefile.PL", into a Makefile.
980       The Unix tool "make" uses this file to manage dependencies and actions
981       to process and install a Perl distribution.
982
984       Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and other
985       authors as noted. All rights reserved.
986
987       This documentation is free; you can redistribute it and/or modify it
988       under the same terms as Perl itself.
989
990       Irrespective of its distribution, all code examples here are in the
991       public domain.  You are permitted and encouraged to use this code and
992       any derivatives thereof in your own programs for fun or for profit as
993       you see fit.  A simple comment in the code giving credit to the FAQ
994       would be courteous but is not required.
995
996
997
998perl v5.12.4                      2011-06-07                       PERLFAQ3(1)
Impressum