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