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