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

NAME

6       perlfaq3 - Programming Tools ($Revision: 1.56 $, $Date: 2005/12/31
7       00:54:37 $)
8

DESCRIPTION

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