1PERLFAQ3(1) Perl Programmers Reference Guide PERLFAQ3(1)
2
3
4
6 perlfaq3 - Programming Tools
7
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 from
59 the source distribution is simplistic and uninteresting, but may still
60 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 cna 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 -Debug)
156 gives you the programmatic hooks into everything you need to write your
157 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 for
221 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 Open Perl IDE
296 http://open-perl-ide.sourceforge.net/
297
298 Open Perl IDE is an integrated development environment for writing
299 and debugging Perl scripts with ActiveState's ActivePerl
300 distribution under Windows 95/98/NT/2000.
301
302 OptiPerl
303 http://www.optiperl.com/
304
305 OptiPerl is a Windows IDE with simulated CGI environment, including
306 debugger and syntax highlighting editor.
307
308 Padre
309 http://padre.perlide.org/
310
311 Padre is cross-platform IDE for Perl written in Perl using the the
312 wxWidgets to provide a native look and feel. It's open source under
313 the Artistic License.
314
315 PerlBuilder
316 http://www.solutionsoft.com/perl.htm
317
318 PerlBuilder is an integrated development environment for Windows
319 that supports Perl development.
320
321 visiPerl+
322 http://helpconsulting.net/visiperl/
323
324 From Help Consulting, for Windows.
325
326 Visual Perl
327 http://www.activestate.com/Products/Visual_Perl/
328
329 Visual Perl is a Visual Studio.NET plug-in from ActiveState.
330
331 Zeus
332 http://www.zeusedit.com/lookmain.html
333
334 Zeus for Window is another Win32 multi-language editor/IDE that
335 comes with support for Perl:
336
337 For editors: if you're on Unix you probably have vi or a vi clone
338 already, and possibly an emacs too, so you may not need to download
339 anything. In any emacs the cperl-mode (M-x cperl-mode) gives you
340 perhaps the best available Perl editing mode in any editor.
341
342 If you are using Windows, you can use any editor that lets you work
343 with plain text, such as NotePad or WordPad. Word processors, such as
344 Microsoft Word or WordPerfect, typically do not work since they insert
345 all sorts of behind-the-scenes information, although some allow you to
346 save files as "Text Only". You can also download text editors designed
347 specifically for programming, such as Textpad ( http://www.textpad.com/
348 ) and UltraEdit ( http://www.ultraedit.com/ ), among others.
349
350 If you are using MacOS, the same concerns apply. MacPerl (for Classic
351 environments) comes with a simple editor. Popular external editors are
352 BBEdit ( http://www.bbedit.com/ ) or Alpha (
353 http://www.his.com/~jguyer/Alpha/Alpha8.html ). MacOS X users can use
354 Unix editors as well.
355
356 GNU Emacs
357 http://www.gnu.org/software/emacs/windows/ntemacs.html
358
359 MicroEMACS
360 http://www.microemacs.de/
361
362 XEmacs
363 http://www.xemacs.org/Download/index.html
364
365 Jed http://space.mit.edu/~davis/jed/
366
367 or a vi clone such as
368
369 Elvis
370 ftp://ftp.cs.pdx.edu/pub/elvis/ http://www.fh-wedel.de/elvis/
371
372 Vile
373 http://dickey.his.com/vile/vile.html
374
375 Vim http://www.vim.org/
376
377 For vi lovers in general, Windows or elsewhere:
378
379 http://www.thomer.com/thomer/vi/vi.html
380
381 nvi ( http://www.bostic.com/vi/ , available from CPAN in src/misc/) is
382 yet another vi clone, unfortunately not available for Windows, but in
383 UNIX platforms you might be interested in trying it out, firstly
384 because strictly speaking it is not a vi clone, it is the real vi, or
385 the new incarnation of it, and secondly because you can embed Perl
386 inside it to use Perl as the scripting language. nvi is not alone in
387 this, though: at least also vim and vile offer an embedded Perl.
388
389 The following are Win32 multilanguage editor/IDEs that support Perl:
390
391 Codewright
392 http://www.borland.com/codewright/
393
394 MultiEdit
395 http://www.MultiEdit.com/
396
397 SlickEdit
398 http://www.slickedit.com/
399
400 ConTEXT
401 http://www.contexteditor.org/
402
403 There is also a toyedit Text widget based editor written in Perl that
404 is distributed with the Tk module on CPAN. The ptkdb (
405 http://ptkdb.sourceforge.net/ ) is a Perl/tk based debugger that acts
406 as a development environment of sorts. Perl Composer (
407 http://perlcomposer.sourceforge.net/ ) is an IDE for Perl/Tk GUI
408 creation.
409
410 In addition to an editor/IDE you might be interested in a more powerful
411 shell environment for Win32. Your options include
412
413 Bash
414 from the Cygwin package ( http://sources.redhat.com/cygwin/ )
415
416 Ksh from the MKS Toolkit ( http://www.mkssoftware.com/ ), or the Bourne
417 shell of the U/WIN environment (
418 http://www.research.att.com/sw/tools/uwin/ )
419
420 Tcsh
421 ftp://ftp.astron.com/pub/tcsh/ , see also
422 http://www.primate.wisc.edu/software/csh-tcsh-book/
423
424 Zsh http://www.zsh.org/
425
426 MKS and U/WIN are commercial (U/WIN is free for educational and
427 research purposes), Cygwin is covered by the GNU General Public License
428 (but that shouldn't matter for Perl use). The Cygwin, MKS, and U/WIN
429 all contain (in addition to the shells) a comprehensive set of standard
430 UNIX toolkit utilities.
431
432 If you're transferring text files between Unix and Windows using FTP be
433 sure to transfer them in ASCII mode so the ends of lines are
434 appropriately converted.
435
436 On Mac OS the MacPerl Application comes with a simple 32k text editor
437 that behaves like a rudimentary IDE. In contrast to the MacPerl
438 Application the MPW Perl tool can make use of the MPW Shell itself as
439 an editor (with no 32k limit).
440
441 Affrus
442 is a full Perl development environment with full debugger support (
443 http://www.latenightsw.com ).
444
445 Alpha
446 is an editor, written and extensible in Tcl, that nonetheless has
447 built in support for several popular markup and programming
448 languages including Perl and HTML (
449 http://www.his.com/~jguyer/Alpha/Alpha8.html ).
450
451 BBEdit and BBEdit Lite
452 are text editors for Mac OS that have a Perl sensitivity mode (
453 http://web.barebones.com/ ).
454
455 Where can I get Perl macros for vi?
456 For a complete version of Tom Christiansen's vi configuration file, see
457 http://www.cpan.org/authors/Tom_Christiansen/scripts/toms.exrc.gz , the
458 standard benchmark file for vi emulators. The file runs best with nvi,
459 the current version of vi out of Berkeley, which incidentally can be
460 built with an embedded Perl interpreter--see
461 http://www.cpan.org/src/misc/ .
462
463 Where can I get perl-mode for emacs?
464 Since Emacs version 19 patchlevel 22 or so, there have been both a
465 perl-mode.el and support for the Perl debugger built in. These should
466 come with the standard Emacs 19 distribution.
467
468 In the Perl source directory, you'll find a directory called "emacs",
469 which contains a cperl-mode that color-codes keywords, provides
470 context-sensitive help, and other nifty things.
471
472 Note that the perl-mode of emacs will have fits with "main'foo" (single
473 quote), and mess up the indentation and highlighting. You are probably
474 using "main::foo" in new Perl code anyway, so this shouldn't be an
475 issue.
476
477 How can I use curses with Perl?
478 The Curses module from CPAN provides a dynamically loadable object
479 module interface to a curses library. A small demo can be found at the
480 directory http://www.cpan.org/authors/Tom_Christiansen/scripts/rep.gz ;
481 this program repeats a command and updates the screen as needed,
482 rendering rep ps axu similar to top.
483
484 How can I write a GUI (X, Tk, Gtk, etc.) in Perl?
485 (contributed by Ben Morrow)
486
487 There are a number of modules which let you write GUIs in Perl. Most
488 GUI toolkits have a perl interface: an incomplete list follows.
489
490 Tk This works under Unix and Windows, and the current version doesn't
491 look half as bad under Windows as it used to. Some of the gui
492 elements still don't 'feel' quite right, though. The interface is
493 very natural and 'perlish', making it easy to use in small scripts
494 that just need a simple gui. It hasn't been updated in a while.
495
496 Wx This is a Perl binding for the cross-platform wxWidgets toolkit (
497 http://www.wxwidgets.org ). It works under Unix, Win32 and Mac OS
498 X, using native widgets (Gtk under Unix). The interface follows the
499 C++ interface closely, but the documentation is a little sparse for
500 someone who doesn't know the library, mostly just referring you to
501 the C++ documentation.
502
503 Gtk and Gtk2
504 These are Perl bindings for the Gtk toolkit ( http://www.gtk.org ).
505 The interface changed significantly between versions 1 and 2 so
506 they have separate Perl modules. It runs under Unix, Win32 and Mac
507 OS X (currently it requires an X server on Mac OS, but a 'native'
508 port is underway), and the widgets look the same on every plaform:
509 i.e., they don't match the native widgets. As with Wx, the Perl
510 bindings follow the C API closely, and the documentation requires
511 you to read the C documentation to understand it.
512
513 Win32::GUI
514 This provides access to most of the Win32 GUI widgets from Perl.
515 Obviously, it only runs under Win32, and uses native widgets. The
516 Perl interface doesn't really follow the C interface: it's been
517 made more Perlish, and the documentation is pretty good. More
518 advanced stuff may require familiarity with the C Win32 APIs, or
519 reference to MSDN.
520
521 CamelBones
522 CamelBones ( http://camelbones.sourceforge.net ) is a Perl
523 interface to Mac OS X's Cocoa GUI toolkit, and as such can be used
524 to produce native GUIs on Mac OS X. It's not on CPAN, as it
525 requires frameworks that CPAN.pm doesn't know how to install, but
526 installation is via the standard OSX package installer. The Perl
527 API is, again, very close to the ObjC API it's wrapping, and the
528 documentation just tells you how to translate from one to the
529 other.
530
531 Qt There is a Perl interface to TrollTech's Qt toolkit, but it does
532 not appear to be maintained.
533
534 Athena
535 Sx is an interface to the Athena widget set which comes with X, but
536 again it appears not to be much used nowadays.
537
538 How can I make my Perl program run faster?
539 The best way to do this is to come up with a better algorithm. This
540 can often make a dramatic difference. Jon Bentley's book Programming
541 Pearls (that's not a misspelling!) has some good tips on optimization,
542 too. Advice on benchmarking boils down to: benchmark and profile to
543 make sure you're optimizing the right part, look for better algorithms
544 instead of microtuning your code, and when all else fails consider just
545 buying faster hardware. You will probably want to read the answer to
546 the earlier question "How do I profile my Perl programs?" if you
547 haven't done so already.
548
549 A different approach is to autoload seldom-used Perl code. See the
550 AutoSplit and AutoLoader modules in the standard distribution for that.
551 Or you could locate the bottleneck and think about writing just that
552 part in C, the way we used to take bottlenecks in C code and write them
553 in assembler. Similar to rewriting in C, modules that have critical
554 sections can be written in C (for instance, the PDL module from CPAN).
555
556 If you're currently linking your perl executable to a shared libc.so,
557 you can often gain a 10-25% performance benefit by rebuilding it to
558 link with a static libc.a instead. This will make a bigger perl
559 executable, but your Perl programs (and programmers) may thank you for
560 it. See the INSTALL file in the source distribution for more
561 information.
562
563 The undump program was an ancient attempt to speed up Perl program by
564 storing the already-compiled form to disk. This is no longer a viable
565 option, as it only worked on a few architectures, and wasn't a good
566 solution anyway.
567
568 How can I make my Perl program take less memory?
569 When it comes to time-space tradeoffs, Perl nearly always prefers to
570 throw memory at a problem. Scalars in Perl use more memory than
571 strings in C, arrays take more than that, and hashes use even more.
572 While there's still a lot to be done, recent releases have been
573 addressing these issues. For example, as of 5.004, duplicate hash keys
574 are shared amongst all hashes using them, so require no reallocation.
575
576 In some cases, using substr() or vec() to simulate arrays can be highly
577 beneficial. For example, an array of a thousand booleans will take at
578 least 20,000 bytes of space, but it can be turned into one 125-byte bit
579 vector--a considerable memory savings. The standard Tie::SubstrHash
580 module can also help for certain types of data structure. If you're
581 working with specialist data structures (matrices, for instance)
582 modules that implement these in C may use less memory than equivalent
583 Perl modules.
584
585 Another thing to try is learning whether your Perl was compiled with
586 the system malloc or with Perl's builtin malloc. Whichever one it is,
587 try using the other one and see whether this makes a difference.
588 Information about malloc is in the INSTALL file in the source
589 distribution. You can find out whether you are using perl's malloc by
590 typing "perl -V:usemymalloc".
591
592 Of course, the best way to save memory is to not do anything to waste
593 it in the first place. Good programming practices can go a long way
594 toward this:
595
596 · Don't slurp!
597
598 Don't read an entire file into memory if you can process it line by
599 line. Or more concretely, use a loop like this:
600
601 #
602 # Good Idea
603 #
604 while (<FILE>) {
605 # ...
606 }
607
608 instead of this:
609
610 #
611 # Bad Idea
612 #
613 @data = <FILE>;
614 foreach (@data) {
615 # ...
616 }
617
618 When the files you're processing are small, it doesn't much matter
619 which way you do it, but it makes a huge difference when they start
620 getting larger.
621
622 · Use map and grep selectively
623
624 Remember that both map and grep expect a LIST argument, so doing
625 this:
626
627 @wanted = grep {/pattern/} <FILE>;
628
629 will cause the entire file to be slurped. For large files, it's
630 better to loop:
631
632 while (<FILE>) {
633 push(@wanted, $_) if /pattern/;
634 }
635
636 · Avoid unnecessary quotes and stringification
637
638 Don't quote large strings unless absolutely necessary:
639
640 my $copy = "$large_string";
641
642 makes 2 copies of $large_string (one for $copy and another for the
643 quotes), whereas
644
645 my $copy = $large_string;
646
647 only makes one copy.
648
649 Ditto for stringifying large arrays:
650
651 {
652 local $, = "\n";
653 print @big_array;
654 }
655
656 is much more memory-efficient than either
657
658 print join "\n", @big_array;
659
660 or
661
662 {
663 local $" = "\n";
664 print "@big_array";
665 }
666
667 · Pass by reference
668
669 Pass arrays and hashes by reference, not by value. For one thing,
670 it's the only way to pass multiple lists or hashes (or both) in a
671 single call/return. It also avoids creating a copy of all the
672 contents. This requires some judgement, however, because any
673 changes will be propagated back to the original data. If you really
674 want to mangle (er, modify) a copy, you'll have to sacrifice the
675 memory needed to make one.
676
677 · Tie large variables to disk.
678
679 For "big" data stores (i.e. ones that exceed available memory)
680 consider using one of the DB modules to store it on disk instead of
681 in RAM. This will incur a penalty in access time, but that's
682 probably better than causing your hard disk to thrash due to
683 massive swapping.
684
685 Is it safe to return a reference to local or lexical data?
686 Yes. Perl's garbage collection system takes care of this so everything
687 works out right.
688
689 sub makeone {
690 my @a = ( 1 .. 10 );
691 return \@a;
692 }
693
694 for ( 1 .. 10 ) {
695 push @many, makeone();
696 }
697
698 print $many[4][5], "\n";
699
700 print "@many\n";
701
702 How can I free an array or hash so my program shrinks?
703 (contributed by Michael Carman)
704
705 You usually can't. Memory allocated to lexicals (i.e. my() variables)
706 cannot be reclaimed or reused even if they go out of scope. It is
707 reserved in case the variables come back into scope. Memory allocated
708 to global variables can be reused (within your program) by using
709 undef() and/or delete().
710
711 On most operating systems, memory allocated to a program can never be
712 returned to the system. That's why long-running programs sometimes re-
713 exec themselves. Some operating systems (notably, systems that use
714 mmap(2) for allocating large chunks of memory) can reclaim memory that
715 is no longer used, but on such systems, perl must be configured and
716 compiled to use the OS's malloc, not perl's.
717
718 In general, memory allocation and de-allocation isn't something you can
719 or should be worrying about much in Perl.
720
721 See also "How can I make my Perl program take less memory?"
722
723 How can I make my CGI script more efficient?
724 Beyond the normal measures described to make general Perl programs
725 faster or smaller, a CGI program has additional issues. It may be run
726 several times per second. Given that each time it runs it will need to
727 be re-compiled and will often allocate a megabyte or more of system
728 memory, this can be a killer. Compiling into C isn't going to help you
729 because the process start-up overhead is where the bottleneck is.
730
731 There are two popular ways to avoid this overhead. One solution
732 involves running the Apache HTTP server (available from
733 http://www.apache.org/ ) with either of the mod_perl or mod_fastcgi
734 plugin modules.
735
736 With mod_perl and the Apache::Registry module (distributed with
737 mod_perl), httpd will run with an embedded Perl interpreter which pre-
738 compiles your script and then executes it within the same address space
739 without forking. The Apache extension also gives Perl access to the
740 internal server API, so modules written in Perl can do just about
741 anything a module written in C can. For more on mod_perl, see
742 http://perl.apache.org/
743
744 With the FCGI module (from CPAN) and the mod_fastcgi module (available
745 from http://www.fastcgi.com/ ) each of your Perl programs becomes a
746 permanent CGI daemon process.
747
748 Both of these solutions can have far-reaching effects on your system
749 and on the way you write your CGI programs, so investigate them with
750 care.
751
752 See
753 http://www.cpan.org/modules/by-category/15_World_Wide_Web_HTML_HTTP_CGI/
754 .
755
756 How can I hide the source for my Perl program?
757 Delete it. :-) Seriously, there are a number of (mostly unsatisfactory)
758 solutions with varying levels of "security".
759
760 First of all, however, you can't take away read permission, because the
761 source code has to be readable in order to be compiled and interpreted.
762 (That doesn't mean that a CGI script's source is readable by people on
763 the web, though--only by people with access to the filesystem.) So you
764 have to leave the permissions at the socially friendly 0755 level.
765
766 Some people regard this as a security problem. If your program does
767 insecure things and relies on people not knowing how to exploit those
768 insecurities, it is not secure. It is often possible for someone to
769 determine the insecure things and exploit them without viewing the
770 source. Security through obscurity, the name for hiding your bugs
771 instead of fixing them, is little security indeed.
772
773 You can try using encryption via source filters (Starting from Perl 5.8
774 the Filter::Simple and Filter::Util::Call modules are included in the
775 standard distribution), but any decent programmer will be able to
776 decrypt it. You can try using the byte code compiler and interpreter
777 described later in perlfaq3, but the curious might still be able to de-
778 compile it. You can try using the native-code compiler described later,
779 but crackers might be able to disassemble it. These pose varying
780 degrees of difficulty to people wanting to get at your code, but none
781 can definitively conceal it (true of every language, not just Perl).
782
783 It is very easy to recover the source of Perl programs. You simply
784 feed the program to the perl interpreter and use the modules in the B::
785 hierarchy. The B::Deparse module should be able to defeat most
786 attempts to hide source. Again, this is not unique to Perl.
787
788 If you're concerned about people profiting from your code, then the
789 bottom line is that nothing but a restrictive license will give you
790 legal security. License your software and pepper it with threatening
791 statements like "This is unpublished proprietary software of XYZ Corp.
792 Your access to it does not give you permission to use it blah blah
793 blah." We are not lawyers, of course, so you should see a lawyer if
794 you want to be sure your license's wording will stand up in court.
795
796 How can I compile my Perl program into byte code or C?
797 (contributed by brian d foy)
798
799 In general, you can't do this. There are some things that may work for
800 your situation though. People usually ask this question because they
801 want to distribute their works without giving away the source code, and
802 most solutions trade disk space for convenience. You probably won't
803 see much of a speed increase either, since most solutions simply bundle
804 a Perl interpreter in the final product (but see "How can I make my
805 Perl program run faster?").
806
807 The Perl Archive Toolkit ( http://par.perl.org/ ) is Perl's analog to
808 Java's JAR. It's freely available and on CPAN (
809 http://search.cpan.org/dist/PAR/ ).
810
811 There are also some commercial products that may work for you, although
812 you have to buy a license for them.
813
814 The Perl Dev Kit ( http://www.activestate.com/Products/Perl_Dev_Kit/ )
815 from ActiveState can "Turn your Perl programs into ready-to-run
816 executables for HP-UX, Linux, Solaris and Windows."
817
818 Perl2Exe ( http://www.indigostar.com/perl2exe.htm ) is a command line
819 program for converting perl scripts to executable files. It targets
820 both Windows and unix platforms.
821
822 How can I get "#!perl" to work on [MS-DOS,NT,...]?
823 For OS/2 just use
824
825 extproc perl -S -your_switches
826
827 as the first line in "*.cmd" file ("-S" due to a bug in cmd.exe's
828 "extproc" handling). For DOS one should first invent a corresponding
829 batch file and codify it in "ALTERNATE_SHEBANG" (see the dosish.h file
830 in the source distribution for more information).
831
832 The Win95/NT installation, when using the ActiveState port of Perl,
833 will modify the Registry to associate the ".pl" extension with the perl
834 interpreter. If you install another port, perhaps even building your
835 own Win95/NT Perl from the standard sources by using a Windows port of
836 gcc (e.g., with cygwin or mingw32), then you'll have to modify the
837 Registry yourself. In addition to associating ".pl" with the
838 interpreter, NT people can use: "SET PATHEXT=%PATHEXT%;.PL" to let them
839 run the program "install-linux.pl" merely by typing "install-linux".
840
841 Under "Classic" MacOS, a perl program will have the appropriate Creator
842 and Type, so that double-clicking them will invoke the MacPerl
843 application. Under Mac OS X, clickable apps can be made from any "#!"
844 script using Wil Sanchez' DropScript utility:
845 http://www.wsanchez.net/software/ .
846
847 IMPORTANT!: Whatever you do, PLEASE don't get frustrated, and just
848 throw the perl interpreter into your cgi-bin directory, in order to get
849 your programs working for a web server. This is an EXTREMELY big
850 security risk. Take the time to figure out how to do it correctly.
851
852 Can I write useful Perl programs on the command line?
853 Yes. Read perlrun for more information. Some examples follow. (These
854 assume standard Unix shell quoting rules.)
855
856 # sum first and last fields
857 perl -lane 'print $F[0] + $F[-1]' *
858
859 # identify text files
860 perl -le 'for(@ARGV) {print if -f && -T _}' *
861
862 # remove (most) comments from C program
863 perl -0777 -pe 's{/\*.*?\*/}{}gs' foo.c
864
865 # make file a month younger than today, defeating reaper daemons
866 perl -e '$X=24*60*60; utime(time(),time() + 30 * $X,@ARGV)' *
867
868 # find first unused uid
869 perl -le '$i++ while getpwuid($i); print $i'
870
871 # display reasonable manpath
872 echo $PATH | perl -nl -072 -e '
873 s![^/+]*$!man!&&-d&&!$s{$_}++&&push@m,$_;END{print"@m"}'
874
875 OK, the last one was actually an Obfuscated Perl Contest entry. :-)
876
877 Why don't Perl one-liners work on my DOS/Mac/VMS system?
878 The problem is usually that the command interpreters on those systems
879 have rather different ideas about quoting than the Unix shells under
880 which the one-liners were created. On some systems, you may have to
881 change single-quotes to double ones, which you must NOT do on Unix or
882 Plan9 systems. You might also have to change a single % to a %%.
883
884 For example:
885
886 # Unix (including Mac OS X)
887 perl -e 'print "Hello world\n"'
888
889 # DOS, etc.
890 perl -e "print \"Hello world\n\""
891
892 # Mac Classic
893 print "Hello world\n"
894 (then Run "Myscript" or Shift-Command-R)
895
896 # MPW
897 perl -e 'print "Hello world\n"'
898
899 # VMS
900 perl -e "print ""Hello world\n"""
901
902 The problem is that none of these examples are reliable: they depend on
903 the command interpreter. Under Unix, the first two often work. Under
904 DOS, it's entirely possible that neither works. If 4DOS was the
905 command shell, you'd probably have better luck like this:
906
907 perl -e "print <Ctrl-x>"Hello world\n<Ctrl-x>""
908
909 Under the Mac, it depends which environment you are using. The MacPerl
910 shell, or MPW, is much like Unix shells in its support for several
911 quoting variants, except that it makes free use of the Mac's non-ASCII
912 characters as control characters.
913
914 Using qq(), q(), and qx(), instead of "double quotes", 'single quotes',
915 and `backticks`, may make one-liners easier to write.
916
917 There is no general solution to all of this. It is a mess.
918
919 [Some of this answer was contributed by Kenneth Albanowski.]
920
921 Where can I learn about CGI or Web programming in Perl?
922 For modules, get the CGI or LWP modules from CPAN. For textbooks, see
923 the two especially dedicated to web stuff in the question on books.
924 For problems and questions related to the web, like "Why do I get 500
925 Errors" or "Why doesn't it run from the browser right when it runs fine
926 on the command line", see the troubleshooting guides and references in
927 perlfaq9 or in the CGI MetaFAQ:
928
929 http://www.perl.org/CGI_MetaFAQ.html
930
931 Where can I learn about object-oriented Perl programming?
932 A good place to start is perltoot, and you can use perlobj, perlboot,
933 perltoot, perltooc, and perlbot for reference.
934
935 A good book on OO on Perl is the "Object-Oriented Perl" by Damian
936 Conway from Manning Publications, or "Intermediate Perl" by Randal
937 Schwartz, brian d foy, and Tom Phoenix from O'Reilly Media.
938
939 Where can I learn about linking C with Perl?
940 If you want to call C from Perl, start with perlxstut, moving on to
941 perlxs, xsubpp, and perlguts. If you want to call Perl from C, then
942 read perlembed, perlcall, and perlguts. Don't forget that you can
943 learn a lot from looking at how the authors of existing extension
944 modules wrote their code and solved their problems.
945
946 You might not need all the power of XS. The Inline::C module lets you
947 put C code directly in your Perl source. It handles all the magic to
948 make it work. You still have to learn at least some of the perl API but
949 you won't have to deal with the complexity of the XS support files.
950
951 I've read perlembed, perlguts, etc., but I can't embed perl in my C
952 program; what am I doing wrong?
953 Download the ExtUtils::Embed kit from CPAN and run `make test'. If the
954 tests pass, read the pods again and again and again. If they fail, see
955 perlbug and send a bug report with the output of "make test
956 TEST_VERBOSE=1" along with "perl -V".
957
958 When I tried to run my script, I got this message. What does it mean?
959 A complete list of Perl's error messages and warnings with explanatory
960 text can be found in perldiag. You can also use the splain program
961 (distributed with Perl) to explain the error messages:
962
963 perl program 2>diag.out
964 splain [-v] [-p] diag.out
965
966 or change your program to explain the messages for you:
967
968 use diagnostics;
969
970 or
971
972 use diagnostics -verbose;
973
974 What's MakeMaker?
975 (contributed by brian d foy)
976
977 The "ExtUtils::MakeMaker" module, better known simply as "MakeMaker",
978 turns a Perl script, typically called "Makefile.PL", into a Makefile.
979 The unix tool "make" uses this file to manage dependencies and actions
980 to process and install a Perl distribution.
981
983 Revision: $Revision$
984
985 Date: $Date$
986
987 See perlfaq for source control details and availability.
988
990 Copyright (c) 1997-2009 Tom Christiansen, Nathan Torkington, and other
991 authors as noted. All rights reserved.
992
993 This documentation is free; you can redistribute it and/or modify it
994 under the same terms as Perl itself.
995
996 Irrespective of its distribution, all code examples here are in the
997 public domain. You are permitted and encouraged to use this code and
998 any derivatives thereof in your own programs for fun or for profit as
999 you see fit. A simple comment in the code giving credit to the FAQ
1000 would be courteous but is not required.
1001
1002
1003
1004perl v5.10.1 2009-08-15 PERLFAQ3(1)