.\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.14 .\" .\" Standard preamble: .\" ======================================================================== .de Sh \" Subsection heading .br .if t .Sp .ne 5 .PP \fB\\$1\fR .PP .. .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. | will give a .\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to .\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C' .\" expand to `' in nroff, nothing in troff, for use with C<>. .tr \(*W-|\(bv\*(Tr .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' 'br\} .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . nr % 0 . rr F .\} .\" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .hy 0 .if n .na .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "PERLFAQ3 1" .TH PERLFAQ3 7 "2003-11-25" "perl v5.8.3" "Perl Programmers Reference Guide" .SH "NAME" perlfaq3 \- 編程工具 (2003/11/24 19:55:50) .SH "DESCRIPTION 描述" .IX Header "DESCRIPTION" 編程工具和編程支持 .Sh "我如何作 (任何事)?" .IX Subsection "How do I do (anything)?" 你到 CPAN(見 perlfaq2)找過了嗎?也許別人已經寫了某個模組可以解決你的問題。你查過相關的說明文件了嗎 (man pages)?以下是一份概要的索引: .PP .Vb 12 \& 基礎Basics perldata, perlvar, perlsyn, perlop, perlsub \& 執行Execution perlrun, perldebug \& 函數Functions perlfunc \& 對象Objects perlref, perlmod, perlobj, perltie \& 數據結構Data Structures perlref, perllol, perldsc \& 模塊Modules perlmod, perlmodlib, perlsub \& 正則表達式Regexes perlre, perlfunc, perlop, perllocale \& 移植Moving to perl5 perltrap, perl \& 連接Linking w/C perlxstut, perlxs, perlcall, perlguts, perlembed \& 其他Various http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz \& (這不是一個手冊頁,但是仍然很有用 \& 是有關 Perl 技術的大量技巧) .Ve .PP perltoc裏有一份粗略的 perl 說明文件組的目錄 .Sh "如何以交互的方式使用 Perl?" .IX Subsection "How can I use Perl interactively?" 典型的作法是使用 perldebug(1)說明文件裏提到的 Perl 除蟲器,在一個「空的」(譯者:即不存在的)程式上執行,像這樣: .PP .Vb 1 \& perl -de 42 .Ve .PP 接下來所打入的任意合法 Perl程式碼皆會立刻被計算。同時,你可以檢查符號表 (symbol table)、取得堆疊的記錄 (stack backtraces)、檢視變數值、設定阻斷點 (set breakpoints) 以及其他符號式除蟲器 (symbolic debuggers) 所能作的動作。 .Sh "有 Perl shell嗎?" .IX Subsection "Is there a Perl shell?" The psh (Perl sh) is currently at version 1.8. The Perl Shell is a shell that combines the interactive nature of a Unix shell with the power of Perl. The goal is a full featured shell that behaves as expected for normal shell activity and uses Perl syntax and functionality for control-flow statements and other things. You can get psh at http://www.focusresearch.com/gregor/psh/ . .PP Zoidberg is a similar project and provides a shell written in perl, configured in perl and operated in perl. It is intended as a login shell and development environment. It can be found at http://zoidberg.sf.net/ or your local \s-1CPAN\s0 mirror. .PP The Shell.pm module (distributed with Perl) makes Perl try commands which aren't part of the Perl language as shell commands. perlsh from the source distribution is simplistic and uninteresting, but may still be what you want. .Sh "怎樣查找我的系統中安裝了哪些模塊?" .IX Subsection "How do I find which modules are installed on my system?" You can use the ExtUtils::Installed module to show all installed distributions, although it can take awhile to do its magic. The standard library which comes with Perl just shows up as \*(L"Perl\*(R" (although you can get those with Module::CoreList). .PP .Vb 1 \& use ExtUtils::Installed; .Ve .PP .Vb 2 \& my $inst = ExtUtils::Installed->new(); \& my @modules = $inst->modules(); .Ve .PP If you want a list of all of the Perl module filenames, you can use File::Find::Rule. .PP .Vb 1 \& use File::Find::Rule; .Ve .PP .Vb 1 \& my @files = File::Find::Rule->file()->name( '*.pm' )->in( @INC ); .Ve .PP If you do not have that module, you can do the same thing with File::Find which is part of the standard library. .PP .Vb 2 \& use File::Find; \& my @files; .Ve .PP .Vb 2 \& find sub { push @files, $File::Find::name if -f _ && /\e.pm$/ }, \& @INC; .Ve .PP .Vb 1 \& print join "\en", @files; .Ve .PP If you simply need to quickly check to see if a module is available, you can check for its documentation. If you can read the documentation the module is most likely installed. If you cannot read the documentation, the module might not have any (in rare cases). .PP .Vb 1 \& prompt% perldoc Module::Name .Ve .PP You can also try to include the module in a one-liner to see if perl finds it. .PP .Vb 1 \& perl -MModule::Name -e1 .Ve .Sh "如何替我的 Perl 程式除蟲?" .IX Subsection "How do I debug my Perl programs?" 你用過 \f(CW\*(C`use warnings\*(C'\fR 或 \f(CW\*(C`\-w\*(C'\fR 嗎?它們啓用警告模式,來檢測不確定的代碼。 .PP 你用過 \f(CW\*(C`use strict\*(C'\fR 嗎?It prevents you from using symbolic references, makes you predeclare any subroutines that you call as bare words, and (probably most importantly) forces you to predeclare your variables with \f(CW\*(C`my\*(C'\fR, \f(CW\*(C`our\*(C'\fR, or \f(CW\*(C`use vars\*(C'\fR. .PP Did you check the return values of each and every system call? The operating system (and thus Perl) tells you whether they worked, and if not why. .PP .Vb 2 \& open(FH, "> /etc/cantwrite") \& or die "Couldn't write to /etc/cantwrite: $!\en"; .Ve .PP Did you read perltrap? It's full of gotchas for old and new Perl programmers and even has sections for those of you who are upgrading from languages like \fIawk\fR and \fIC\fR. .PP Have you tried the Perl debugger, described in perldebug? You can step through your program and see what it's doing and thus work out why what it's doing isn't what it should be doing. .Sh "如何檢測 (profile) 我的 perl 程式?" .IX Subsection "How do I profile my Perl programs?" 你該自 CPAN抓取 Devel::DProf 模組,並且使用 perl 標準套件所附的 Benchmark.pm。 Benchmark.pm讓你測量程式碼的某部份在執行上所花的時間,而 Devel::DProf則詳細地替你分析哪一部份的程式用掉多少時間。 .PP Here's a sample use of Benchmark: .PP .Vb 1 \& use Benchmark; .Ve .PP .Vb 2 \& @junk = `cat /etc/motd`; \& $count = 10_000; .Ve .PP .Vb 8 \& timethese($count, { \& 'map' => sub { my @a = @junk; \& map { s/a/b/ } @a; \& return @a }, \& 'for' => sub { my @a = @junk; \& for (@a) { s/a/b/ }; \& return @a }, \& }); .Ve .PP This is what it prints (on one machine\*(--your results will be dependent on your hardware, operating system, and the load on your machine): .PP .Vb 3 \& Benchmark: timing 10000 iterations of for, map... \& for: 4 secs ( 3.97 usr 0.01 sys = 3.98 cpu) \& map: 6 secs ( 4.97 usr 0.00 sys = 4.97 cpu) .Ve .PP Be aware that a good benchmark is very hard to write. It only tests the data you give it and proves little about the differing complexities of contrasting algorithms. .Sh "如何替我的 Perl程式作交叉參考?" .IX Subsection "How do I cross-reference my Perl programs?" B::Xref模組可 以替你的 Perl程式製作 cross-reference報告。用法是: .PP .Vb 1 \& perl -MO=Xref[,OPTIONS] scriptname.plx .Ve .Sh "有 Perl專用的美化列印程式嗎?" .IX Subsection "Is there a pretty-printer (formatter) for Perl?" Perltidy is a Perl script which indents and reformats Perl scripts to make them easier to read by trying to follow the rules of the perlstyle. If you write Perl scripts, or spend much time reading them, you will probably find it useful. It is available at http://perltidy.sourceforge.net .PP Of course, if you simply follow the guidelines in perlstyle, you shouldn't need to reformat. The habit of formatting your code as you write it will help prevent bugs. Your editor can and should help you with this. The perl-mode or newer cperl-mode for emacs can provide remarkable amounts of help with most (but not all) code, and even less programmable editors can provide significant assistance. Tom Christiansen and many other \s-1VI\s0 users swear by the following settings in vi and its clones: .PP .Vb 2 \& set ai sw=4 \& map! ^O {^M}^[O^T .Ve .PP Put that in your \fI.exrc\fR file (replacing the caret characters with control characters) and away you go. In insert mode, ^T is for indenting, ^D is for undenting, and ^O is for blockdenting\*(-- as it were. A more complete example, with comments, can be found at http://www.cpan.org/authors/id/TOMC/scripts/toms.exrc.gz .PP The a2ps http://www\-inf.enst.fr/%7Edemaille/a2ps/black+white.ps.gz does lots of things related to generating nicely printed output of documents, as does enscript at http://people.ssh.fi/mtr/genscript/ . .Sh "有 Perl的 ctags 嗎?" .IX Subsection "Is there a ctags for Perl?" Recent versions of ctags do much more than older versions did. \&\s-1EXUBERANT\s0 \s-1CTAGS\s0 is available from http://ctags.sourceforge.net/ and does a good job of making tags files for perl code. .PP There is also a simple one at http://www.cpan.org/authors/id/TOMC/scripts/ptags.gz which may do the trick. It can be easy to hack this into what you want. .Sh "Is there an \s-1IDE\s0 or Windows Perl Editor?" .IX Subsection "Is there an IDE or Windows Perl Editor?" Perl programs are just plain text, so any editor will do. .PP If you're on Unix, you already have an IDE\*(--Unix itself. The \s-1UNIX\s0 philosophy is the philosophy of several small tools that each do one thing and do it well. It's like a carpenter's toolbox. .PP If you want an \s-1IDE\s0, check the following: .IP "Komodo" 4 .IX Item "Komodo" ActiveState's cross-platform (as of April 2001 Windows and Linux), multi-language \s-1IDE\s0 has Perl support, including a regular expression debugger and remote debugging ( http://www.ActiveState.com/Products/Komodo/index.html ). (Visual Perl, a Visual Studio.NET plug-in is currently (early 2001) in beta ( http://www.ActiveState.com/Products/VisualPerl/index.html )). .IP "The Object System" 4 .IX Item "The Object System" ( http://www.castlelink.co.uk/object_system/ ) is a Perl web applications development \s-1IDE\s0, apparently for any platform that runs Perl. .IP "Open Perl \s-1IDE\s0" 4 .IX Item "Open Perl IDE" ( http://open\-perl\-ide.sourceforge.net/ ) Open Perl \s-1IDE\s0 is an integrated development environment for writing and debugging Perl scripts with ActiveState's ActivePerl distribution under Windows 95/98/NT/2000. .IP "PerlBuilder" 4 .IX Item "PerlBuilder" ( http://www.solutionsoft.com/perl.htm ) is an integrated development environment for Windows that supports Perl development. .IP "visiPerl+" 4 .IX Item "visiPerl+" ( http://helpconsulting.net/visiperl/ ) From Help Consulting, for Windows. .IP "OptiPerl" 4 .IX Item "OptiPerl" ( http://www.optiperl.com/ ) is a Windows \s-1IDE\s0 with simulated \s-1CGI\s0 environment, including debugger and syntax highlighting editor. .PP For editors: if you're on Unix you probably have vi or a vi clone already, and possibly an emacs too, so you may not need to download anything. In any emacs the cperl-mode (M\-x cperl\-mode) gives you perhaps the best available Perl editing mode in any editor. .PP If you are using Windows, you can use any editor that lets you work with plain text, such as NotePad or WordPad. Word processors, such as Microsoft Word or WordPerfect, typically do not work since they insert all sorts of behind-the-scenes information, although some allow you to save files as \*(L"Text Only\*(R". You can also download text editors designed specifically for programming, such as Textpad ( http://www.textpad.com/ ) and UltraEdit ( http://www.ultraedit.com/ ), among others. .PP If you are using MacOS, the same concerns apply. MacPerl (for Classic environments) comes with a simple editor. Popular external editors are BBEdit ( http://www.bbedit.com/ ) or Alpha ( http://www.kelehers.org/alpha/ ). MacOS X users can use Unix editors as well. .IP "\s-1GNU\s0 Emacs" 4 .IX Item "GNU Emacs" http://www.gnu.org/software/emacs/windows/ntemacs.html .IP "MicroEMACS" 4 .IX Item "MicroEMACS" http://www.microemacs.de/ .IP "XEmacs" 4 .IX Item "XEmacs" http://www.xemacs.org/Download/index.html .IP "Jed" 4 .IX Item "Jed" http://space.mit.edu/~davis/jed/ .PP or a vi clone such as .IP "Elvis" 4 .IX Item "Elvis" ftp://ftp.cs.pdx.edu/pub/elvis/ http://www.fh\-wedel.de/elvis/ .IP "Vile" 4 .IX Item "Vile" http://dickey.his.com/vile/vile.html .IP "Vim" 4 .IX Item "Vim" http://www.vim.org/ .PP For vi lovers in general, Windows or elsewhere: .PP .Vb 1 \& http://www.thomer.com/thomer/vi/vi.html .Ve .PP nvi ( http://www.bostic.com/vi/ , available from \s-1CPAN\s0 in src/misc/) is yet another vi clone, unfortunately not available for Windows, but in \&\s-1UNIX\s0 platforms you might be interested in trying it out, firstly because strictly speaking it is not a vi clone, it is the real vi, or the new incarnation of it, and secondly because you can embed Perl inside it to use Perl as the scripting language. nvi is not alone in this, though: at least also vim and vile offer an embedded Perl. .PP The following are Win32 multilanguage editor/IDESs that support Perl: .IP "Codewright" 4 .IX Item "Codewright" http://www.starbase.com/ .IP "MultiEdit" 4 .IX Item "MultiEdit" http://www.MultiEdit.com/ .IP "SlickEdit" 4 .IX Item "SlickEdit" http://www.slickedit.com/ .PP There is also a toyedit Text widget based editor written in Perl that is distributed with the Tk module on \s-1CPAN\s0. The ptkdb ( http://world.std.com/~aep/ptkdb/ ) is a Perl/tk based debugger that acts as a development environment of sorts. Perl Composer ( http://perlcomposer.sourceforge.net/ ) is an \s-1IDE\s0 for Perl/Tk \&\s-1GUI\s0 creation. .PP In addition to an editor/IDE you might be interested in a more powerful shell environment for Win32. Your options include .IP "Bash" 4 .IX Item "Bash" from the Cygwin package ( http://sources.redhat.com/cygwin/ ) .IP "Ksh" 4 .IX Item "Ksh" from the \s-1MKS\s0 Toolkit ( http://www.mks.com/ ), or the Bourne shell of the U/WIN environment ( http://www.research.att.com/sw/tools/uwin/ ) .IP "Tcsh" 4 .IX Item "Tcsh" ftp://ftp.astron.com/pub/tcsh/ , see also http://www.primate.wisc.edu/software/csh\-tcsh\-book/ .IP "Zsh" 4 .IX Item "Zsh" ftp://ftp.blarg.net/users/amol/zsh/ , see also http://www.zsh.org/ .PP \&\s-1MKS\s0 and U/WIN are commercial (U/WIN is free for educational and research purposes), Cygwin is covered by the \s-1GNU\s0 Public License (but that shouldn't matter for Perl use). The Cygwin, \s-1MKS\s0, and U/WIN all contain (in addition to the shells) a comprehensive set of standard \&\s-1UNIX\s0 toolkit utilities. .PP If you're transferring text files between Unix and Windows using \s-1FTP\s0 be sure to transfer them in \s-1ASCII\s0 mode so the ends of lines are appropriately converted. .PP On Mac \s-1OS\s0 the MacPerl Application comes with a simple 32k text editor that behaves like a rudimentary \s-1IDE\s0. In contrast to the MacPerl Application the \s-1MPW\s0 Perl tool can make use of the \s-1MPW\s0 Shell itself as an editor (with no 32k limit). .IP "BBEdit and BBEdit Lite" 4 .IX Item "BBEdit and BBEdit Lite" are text editors for Mac \s-1OS\s0 that have a Perl sensitivity mode ( http://web.barebones.com/ ). .IP "Alpha" 4 .IX Item "Alpha" is an editor, written and extensible in Tcl, that nonetheless has built in support for several popular markup and programming languages including Perl and \s-1HTML\s0 ( http://alpha.olm.net/ ). .PP Pepper and Pe are programming language sensitive text editors for Mac \&\s-1OS\s0 X and BeOS respectively ( http://www.hekkelman.com/ ). .Sh "哪兒有 vi 用的 Perl 宏?" .IX Subsection "Where can I get Perl macros for vi?" For a complete version of Tom Christiansen's vi configuration file, see http://www.cpan.org/authors/Tom_Christiansen/scripts/toms.exrc.gz , the standard benchmark file for vi emulators. The file runs best with nvi, the current version of vi out of Berkeley, which incidentally can be built with an embedded Perl interpreter\*(--see http://www.cpan.org/src/misc/ . .Sh "給 emacs用的 perl模式又要去哪抓呢?" .IX Subsection "Where can I get perl-mode for emacs?" 從大約 Emacs 19.22版 (version 19 patchlevel 22)起,已內含了 perl-mode.el及 perl 除蟲器的支援。它們應該會和標準的 Emacs 19版一起出貨。 .PP 在 perl原始碼的目錄下,你會找到一個叫作 ``emacs'' 的目錄,裏面包括一個 cperl-mode 可以把程式中的關鍵字上色、提供內文相關的協助以及其它方便的功能。 .PP 注意:``main'foo''(其中的單引號)會讓 emacs的 perl-mode 出問題,並且會弄亂內 縮 (indentation) 與高亮 (hilighting)。不過你本來就該用 ``main::foo''的 (譯者按: main'foo 是表示模組或 package的舊式寫法;新式的 [perl5的]寫法是 main::foo)。 .Sh "如何在 Perl裏使用 curses?" .IX Subsection "How can I use curses with Perl?" The Curses module from \s-1CPAN\s0 provides a dynamically loadable object module interface to a curses library. A small demo can be found at the directory http://www.cpan.org/authors/Tom_Christiansen/scripts/rep.gz ; this program repeats a command and updates the screen as needed, rendering \&\fBrep ps axu\fR similar to \fBtop\fR. .Sh "X或 Tk如何與 Perl配合呢?" .IX Subsection "How can I use X or Tk with Perl?" Tk 模塊是一個完全以 Perl 爲基礎,面向對象的接口,讓你不用學 Tcl也可以使用 Tk工具組。Sx則是 Athena Widget set專用的介面。兩者都可在 CPAN取得。參見分類 http://www.cpan.org/modules/by\-category/08_User_Interfaces/ .PP Invaluable for Perl/Tk programming are the Perl/Tk \s-1FAQ\s0 at http://w4.lns.cornell.edu/%7Epvhp/ptk/ptkTOC.html , the Perl/Tk Reference Guide available at http://www.cpan.org/authors/Stephen_O_Lidie/ , and the online manpages at http://www\-users.cs.umn.edu/%7Eamundson/perl/perltk/toc.html . .Sh "如何不靠 CGI或 Tk 幫助作出簡單的目錄(選單)?" .IX Subsection "How can I generate simple menus without using CGI or Tk?" http://www.cpan.org/authors/id/SKUNZ/perlmenu.v4.0.tar.gz 是個以 curses爲基礎的模組,可以達成你的要求。 .Sh "如何讓我的 Perl程式跑得更快些?" .IX Subsection "How can I make my Perl program run faster?" 最好是能設計一個較好的演算法 (algorithm),這通常會讓程式有大不相同的表現。Jon Bentley's book \fIProgramming Pearls\fR (沒有拼寫錯誤!) 中有些你或許想知道的增進效率小技巧。 Advice on benchmarking boils down to: benchmark and profile to make sure you're optimizing the right part, look for better algorithms instead of microtuning your code, and when all else fails consider just buying faster hardware. You will probably want to read the answer to the earlier question ``How do I profile my Perl programs?'' if you haven't done so already. .PP 其它方法包括自動載入較少使用的 Perl 程式碼。請參看標準 perl 套件中的 AutoSplit及 AutoLoader模組的用法。或當你能斷定程式執行效率的瓶頸在何處時,用 C來寫那個部份,就像用組合語言來撰寫 C程式的瓶頸部份一樣。與此法相近的是使用以 C撰寫瓶 頸部份的模組 (例如 CPAN中的 PDL 模組)。 .PP 如果你目前是將你的 perl直譯器動態連結到 libc.so的話,重新作一份靜態連結到 libc.a的 perl直譯器可以提高 10-25%的執行效能。雖然這會使你的 perl直譯器變得更胖,但你的 Perl程式 (及程式設計者) 或許會因此而感謝你。詳情請參考 perl標準套件原始碼版本中的 INSTALL 檔案。 .PP 使用 undump程式把編譯後的檔案格式存到硬碟裏以加快執行的速度已經是老掉牙的手法了。它已不再是個可行的方法,因爲這方法只有幾種平臺能用,況且它終究不是個治本之 道。 .Sh "如何讓我的 Perl 程序少用一些內存?" .IX Subsection "How can I make my Perl program take less memory?" 當問題變成時間與空間的交易時, Perl 幾乎總是用記憶體來幫忙解決問題。 Perl中的純量 (Scalar) 耗掉的記憶體比 C中的字串形態還多,陣列又更多, 更別談雜湊陣列了 (Hashes)。關於這一點,我們當然還有很多工作得作,近來發布的版本,已開始針對這些問題做改進了。例如, 5.004 版中, 重複的散列鍵 (duplicate hash keys) 由使用它的雜湊陣列共用,這樣就不用再重新定份位置給它了。 .PP 在某些情況下,使用 substr()或 vec()來模擬數組有很大的好處。例如,一個有上千 個布林代數值的陣列將佔用至少 20,000位元組的空間,但是它可以被轉變爲一個 125位元組的位元向量 (bit vector)以節省相當可觀的記憶體。標準套件中的 Tie::SubstrHash模組也能夠幫助特定形態的資料結構節省些記憶體。若你正在和一些特殊的資料結構奮戰 (例如,矩陣),用 C寫的模組所耗掉的記憶體可能低於同功能並用 Perl寫的模組。 .PP 另一件值得一試的是,查一下你的 Perl是以系統內的 malloc 還是 Perl內含的 malloc 編譯起來的。不論是哪個,試着換成另一個,再看看這是否造成任何差別。關於 malloc的資訊可在 perl標準套件原始碼版中的 INSTALL 檔案找到。鍵入 \f(CW\*(C`perl \-V:usemymalloc\*(C'\fR. 就可以知道你是否在使用 perl的 malloc。 .PP Of course, the best way to save memory is to not do anything to waste it in the first place. Good programming practices can go a long way toward this: .IP "* Don't slurp!" 4 .IX Item "Don't slurp!" Don't read an entire file into memory if you can process it line by line. Or more concretely, use a loop like this: .Sp .Vb 6 \& # \& # Good Idea \& # \& while () { \& # ... \& } .Ve .Sp instead of this: .Sp .Vb 7 \& # \& # Bad Idea \& # \& @data = ; \& foreach (@data) { \& # ... \& } .Ve .Sp When the files you're processing are small, it doesn't much matter which way you do it, but it makes a huge difference when they start getting larger. .IP "* Use map and grep selectively" 4 .IX Item "Use map and grep selectively" Remember that both map and grep expect a \s-1LIST\s0 argument, so doing this: .Sp .Vb 1 \& @wanted = grep {/pattern/} ; .Ve .Sp will cause the entire file to be slurped. For large files, it's better to loop: .Sp .Vb 3 \& while () { \& push(@wanted, $_) if /pattern/; \& } .Ve .IP "* Avoid unnecessary quotes and stringification" 4 .IX Item "Avoid unnecessary quotes and stringification" Don't quote large strings unless absolutely necessary: .Sp .Vb 1 \& my $copy = "$large_string"; .Ve .Sp makes 2 copies of \f(CW$large_string\fR (one for \f(CW$copy\fR and another for the quotes), whereas .Sp .Vb 1 \& my $copy = $large_string; .Ve .Sp only makes one copy. .Sp Ditto for stringifying large arrays: .Sp .Vb 4 \& { \& local $, = "\en"; \& print @big_array; \& } .Ve .Sp is much more memory-efficient than either .Sp .Vb 1 \& print join "\en", @big_array; .Ve .Sp or .Sp .Vb 4 \& { \& local $" = "\en"; \& print "@big_array"; \& } .Ve .IP "* Pass by reference" 4 .IX Item "Pass by reference" Pass arrays and hashes by reference, not by value. For one thing, it's the only way to pass multiple lists or hashes (or both) in a single call/return. It also avoids creating a copy of all the contents. This requires some judgment, however, because any changes will be propagated back to the original data. If you really want to mangle (er, modify) a copy, you'll have to sacrifice the memory needed to make one. .IP "* Tie large variables to disk." 4 .IX Item "Tie large variables to disk." For \*(L"big\*(R" data stores (i.e. ones that exceed available memory) consider using one of the \s-1DB\s0 modules to store it on disk instead of in \s-1RAM\s0. This will incur a penalty in access time, but that's probably better than causing your hard disk to thrash due to massive swapping. .Sh "把局部變量的引用返回是不安全的做法嗎?" .IX Subsection "Is it safe to return a reference to local or lexical data?" 這樣是安全的,Perl的資源回收 (garbage collection)系統會解決此問題。 .PP .Vb 4 \& sub makeone { \& my @a = ( 1 .. 10 ); \& return \e@a; \& } .Ve .PP .Vb 3 \& for ( 1 .. 10 ) { \& push @many, makeone(); \& } .Ve .PP .Vb 1 \& print $many[4][5], "\en"; .Ve .PP .Vb 1 \& print "@many\en"; .Ve .Sh "我如何釋放一個數組或散列以縮小我的程式尺寸?" .IX Subsection "How can I free an array or hash so my program shrinks?" 你無法這麼作。系統配置給程式的記憶體是覆水難收。這也是爲何執行很長一段時間的程式有時會重新執行 (re-exec)它們自己的原因。 Some operating systems (notably, systems that use \fImmap\fR\|(2) for allocating large chunks of memory) can reclaim memory that is no longer used, but on such systems, perl must be configured and compiled to use the \s-1OS\s0's malloc, not perl's. .PP 然而,在使用你的變數時,明智地用 my()來定義執行範圍,可讓 Perl在脫離該範圍後 將它們所佔的空間釋放給其它部份的程式。 (注:my()的變數也比全域變數執行起來快 10%。)當然,一個全域變數永遠沒有超出範圍的時候,所以你無法將它佔用的空間自動重新分配,不過,把它 undef() 或/和 delete()會有相同的效果。總之,在 Perl裏,你並不能/應該去擔心太多有關記憶體定址與解除這件事,而我們連添加這項功能(資料形態的預先定址),目前都已在進行中。 .Sh "如何讓我的 CGI腳本 (script)執行起來更有效率?" .IX Subsection "How can I make my CGI script more efficient?" 除了使一般 Perl程式加快或縮小的平常手段外,一個 CGI 程式還有其他的顧慮。也許它每秒會被執行好幾次。每次它執行時,重新編譯所花的時間、加上定址所需的 1 MB以上的系統記憶體,就是一個大殺手。光是編譯成 C 是沒啥幫助的 ,因爲瓶頸在於整個程序開始時所負擔的包袱 (start-up overhead) 。 .PP 最起碼有兩種較流行的方法可以避免這些包袱。一種解法是將 mod_perl 或是 mod_fastcgi其中一個模組加在你所執行的 Apache HTTP server。 .PP 有了 mod_perl 和 Apache::*模組 (從 CPAN取得),httpd執行時會帶起一個內 嵌的 Perl直譯器,而它會預先編譯你的程式,並在不產生其它子程序的情況下用同一個定址空間來執行。Apache 擴充模組亦給 Perl一個連通 server API 的管道,所以用 Perl寫的模組可以做到任何 C寫的模組所具備的功能。詳情請參閱 http://perl.apache.org/ .PP 而有了 FCGI模組 (自 CPAN取得) 和 mod_fastcgi 模塊(從 http://www.fastcgi.com/取得),每個 Perl 程序將成爲一個永久的 CGI 守護進程。 .PP 這些方法對你的系統與你撰寫 CGI程式的方法都有超乎想像之外的影響,所以請小心地使用它們。 .PP 參見 http://www.cpan.org/modules/by\-category/15_World_Wide_Web_HTML_HTTP_CGI/ . .PP A non\-free, commercial product, ``The Velocity Engine for Perl'', (http://www.binevolve.com/ or http://www.binevolve.com/velocigen/ ) might also be worth looking at. It will allow you to increase the performance of your Perl programs, running programs up to 25 times faster than normal \s-1CGI\s0 Perl when running in persistent Perl mode or 4 to 5 times faster without any modification to your existing \s-1CGI\s0 programs. Fully functional evaluation copies are available from the web site. .Sh "如何隱藏 Perl程式的原始碼?" .IX Subsection "How can I hide the source for my Perl program?" 刪除它。 :-) 說真的,有一些具有不同“安全”等級的方法(大部分都不能令人滿意)。 .PP 首先,你 不能拿走讀取權,不然你的程式怎麼被解譯或是編譯呢? (不過那也並不表示一個 CGI程式的原始碼可以被使用者讀取。)所以你得讓檔案權限停留在 0755這個友善的階段。 .PP 有些人認爲這是個安全上的漏洞。不過若你的程式作的是不安全的事情,光仰賴別人看不見這些漏洞、不知從何下手,那麼它依然是不安全的。其實對有些人來說他們並不需要看見程式原始碼便可能判定並揭露這些不安全的部份。透過隱瞞達到的安全,就是不修正臭蟲反而隱藏它們,實際上是沒有安全性可言的。 .PP 你可以試着透過原始碼過濾模組 (CPAN中的 Filter::*)來替原始碼加密。但高手也許有辦法將其解密還原。你也可以用下面提到的 byte code 編譯器與直譯器,但高手也有可能反解譯它。你可以試試後面提到的原生碼編譯器 (native-code compiler),但高手也有可能反組譯它。這些手段都需要不同難度的技巧才能讓別人拿到你的原始碼,但沒有一種能夠很確定地隱藏它。(這對每種語言來說都爲真,不是隻有 Perl) .PP 很容易從 Perl 程序中恢復出源碼。只要將程序作爲 perl 解釋器的參數,並且使用 B:: 中的模塊就可以了。B::Deparse 模塊足以恢復大多數隱藏的代碼。再次的,這不是 Perl 特有的東西。 .PP 如果你所擔心的是別人自你的程式碼中獲利,那麼一紙權限執照是能提供你法律上安全的唯一途徑。註冊你的軟體並且寫份權限說明,再加上一些具威脅性的句子像“這是 XYZ公司未出版的專有軟體。你能擷取它並不代表你具有使用的權限...”之類云云。當然,我們不是律師,所以若你想要你的執照中每一句話在法庭上都站得住腳,就去見個律師吧。 .Sh "如何把我的 Perl程式碼編譯成 byte code或 C?" .IX Subsection "How can I compile my Perl program into byte code or C?" Malcolm Beattie已經寫了一個多功能的後端編譯器,可以從 CPAN取得,它就能做到這兩項功能。它包含在 perl5.005 發佈中,但是仍然是測試版。這代表着若你是個程式設計 員而非尋找萬靈解藥的人,那麼參與其測試就會充滿趣味。 .PP 請了解光是編譯成 C 其本身或在本質上並不能保證它就會跑得快更多。那是因爲除了在運氣好的狀況中有一堆可以衍生成出來的原生形態外,平時的 Perl 執行系統環境依然存在因此依然會花差不多長的執行時間與佔用差不多大小的記憶空間。大多數程式能省下來的不過是編譯時間,這使執行速度頂多快 10-30%。有些罕見的程式能真正從中受利 (例如增快好幾倍),但這還得配合原始碼的微調。 .PP 你或許會驚訝地發現,現行版本的編譯器做出來的執行檔大小跟你的 Perl直譯器一樣大,有時更大些。那是因爲依照現在的寫法,所有的程式皆轉成一個被 eval()的大敘述。只要建造一個動態連結的 libperl.so程式庫,並將之連結起來,你就可以戲劇性地減少這 種浪費。參看 perl原始碼套件中的 INSTALL pod檔案以獲得更詳盡的訊息。如果你用這方法連結你主要的 perl執行檔,就能使它變得很渺小。舉例來說,在作者之一的系 統裏, /usr/bin/perl只有 11k“小”而已! .PP In general, the compiler will do nothing to make a Perl program smaller, faster, more portable, or more secure. In fact, it can make your situation worse. The executable will be bigger, your \s-1VM\s0 system may take longer to load the whole thing, the binary is fragile and hard to fix, and compilation never stopped software piracy in the form of crackers, viruses, or bootleggers. The real advantage of the compiler is merely packaging, and once you see the size of what it makes (well, unless you use a shared \fIlibperl.so\fR), you'll probably want a complete Perl install anyway. .Sh "How can I compile Perl into Java?" .IX Subsection "How can I compile Perl into Java?" You can also integrate Java and Perl with the Perl Resource Kit from O'Reilly and Associates. See http://www.oreilly.com/catalog/prkunix/ . .PP Perl 5.6 comes with Java Perl Lingo, or \s-1JPL\s0. \s-1JPL\s0, still in development, allows Perl code to be called from Java. See jpl/README in the Perl source tree. .ie n .Sh "如何才能讓 "#!perl" 在 [MS-DOS,NT,...] 下起作用?" .el .Sh "如何才能讓 "#!perl" 在 [MS-DOS,NT,...] 下起作用?" .IX Subsection "How can I get #!perl to work on [MS-DOS,NT,...]?" OS/2下只要用: .PP .Vb 1 \& extproc perl -S -your_switches .Ve .PP 當作 \f(CW\*(C`*.cmd\*(C'\fR 檔案的第一行 (\f(CW\*(C`\-S\*(C'\fR 是因 cmd.exe中其 `extproc'處理的臭蟲纔要的)。DOS使用者應先製作一個相對的 batch 檔案然後將它以 ALTERNATIVE_SHEBANG 的方式寫成程式。(更多訊息在原始碼版本的 INSTALL檔案裏) .PP The Win95/NT installation, when using the ActiveState port of Perl, will modify the Registry to associate the \f(CW\*(C`.pl\*(C'\fR extension with the perl interpreter. If you install another port, perhaps even building your own Win95/NT Perl from the standard sources by using a Windows port of gcc (e.g., with cygwin or mingw32), then you'll have to modify the Registry yourself. In addition to associating \f(CW\*(C`.pl\*(C'\fR with the interpreter, \s-1NT\s0 people can use: \f(CW\*(C`SET PATHEXT=%PATHEXT%;.PL\*(C'\fR to let them run the program \f(CW\*(C`install\-linux.pl\*(C'\fR merely by typing \f(CW\*(C`install\-linux\*(C'\fR. .PP 麥金塔的 perl程式將會有適當的創造者與形態 (Creator and Type),所以雙擊它們就會執行這些 perl 應用程式。 .PP 重要:不論你做什麼,請千萬不要因爲覺得沮喪,就把 perl 直譯器丟到你的 cgi-bin目錄下,好讓你的 web 伺服器能執行你的程式。這是一個非常大的安全漏洞。花點時間想想怎樣纔是正確的做法吧。 .Sh "我能利用命令行寫出有用的程式嗎?" .IX Subsection "Can I write useful Perl programs on the command line?" 可以。詳情請看 perlrun。以下有些範例 (假設用的是標準的 Unix shell引言規則)。 .PP .Vb 2 \& # 把第一欄和最後一欄相加 \& perl -lane 'print $F[0] + $F[-1]' * .Ve .PP .Vb 2 \& # 辨別是否爲文字檔 \& perl -le 'for(@ARGV) {print if -f && -T _}' * .Ve .PP .Vb 2 \& # 移除 C程式中的說明 \& perl -0777 -pe 's{/\e*.*?\e*/}{}gs' foo.c .Ve .PP .Vb 2 \& # 讓檔案年輕一個月,躲避 reaper daemons \& perl -e '$X=24*60*60; utime(time(),time() + 30 * $X,@ARGV)' * .Ve .PP .Vb 2 \& # 找出第一個未用的 uid \& perl -le '$i++ while getpwuid($i); print $i' .Ve .PP .Vb 3 \& # 顯示合理的使用說明路徑 (manpath) \& echo $PATH | perl -nl -072 -e ' \& s![^/+]*$!man!&&-d&&!$s{$_}++&&push@m,$_;END{print"@m"}' .Ve .PP 好吧,最後一個例子事實上是「perl程式困惑化」競賽 (Obfuscated Perl)的 參賽作品。 :-) .Sh "爲何一行的 perl 程式無法在我的 DOS/Mac/VMS系統上運作?" .IX Subsection "Why don't Perl one-liners work on my DOS/Mac/VMS system?" 問題通常出在那些系統的命令解譯器對於參數的引用與 Unix shells 所作的解釋不同,而後者很不幸的是這些一行 perl 的生父。在某些系統,也許你得把單引號改成雙引號,但這卻是你萬萬 不可在 Unix或 Plan9系統上作的事。你也許還得把一個 %改成 %%。 .PP 例如: .PP .Vb 2 \& # Unix \& perl -e 'print "Hello world\en"' .Ve .PP .Vb 2 \& # DOS 和其他機器 \& perl -e "print \e"Hello world\en\e"" .Ve .PP .Vb 3 \& # Mac \& print "Hello world\en" \& (然後運行 "Myscript" 或按 Shift-Command-R) .Ve .PP .Vb 2 \& # MPW \& perl -e 'print "Hello world\en"' .Ve .PP .Vb 2 \& # VMS \& perl -e "print ""Hello world\en""" .Ve .PP 問題是,這些方法沒有一個是完全可靠的:它都得看命令解譯器的臉色。在 Unix中,前兩者通常可以用。在 DOS下,兩者可能都沒有用。若 4DOS是命令解譯器,下面此法可能比 較有希望: .PP .Vb 1 \& perl -e "print "Hello world\en"" .Ve .PP 在 Mac 下,端視你所用的環境爲何。 MacPerl所附的 shell,或是 MPW, 其所支援的參數格式有不少都蠻像 Unix shells的,除了它自在地使用 Mac 的非 ASCII字元當成控制字元。 .PP Using \fIqq()\fR, q(), and \fIqx()\fR, instead of \*(L"double quotes\*(R", 'single quotes', and `backticks`, may make one-liners easier to write. .PP 恐怕我得說這問題並沒有一般解。白話一點說,它真是一團亂。 .PP [部份答案是由 Kenneth Albanowski 所提供的。] .Sh "我得去哪裏學 Perl的 CGI或是 Web程式設計呢?" .IX Subsection "Where can I learn about CGI or Web programming in Perl?" 就模組來說,去 CPAN抓 CGI 和 LWP 兩個模組。就書本來看,參考關於書那部份裏特別和 web 相關的問題。若有與 web相關的疑難雜症,像“爲何我收到 500錯誤”或“它在命令列模式下跑得好好的,怎麼不能在瀏覽器下正常執行”時,請參看: .PP .Vb 1 \& http://www.perl.org/CGI_MetaFAQ.html .Ve .Sh "從哪裏可以學習面向對象的 Perl 編程?" .IX Subsection "Where can I learn about object-oriented Perl programming?" perltoot是個好開始,然後你可以再參考 perlobj 和 perlboot,Perltoot,perltooc 以及 perlbot (如果你使用老版本的 Perl,你可能沒有這些。去 http://www.perldoc.com/ 下載吧,但是首先考慮一下升級你的 perl) .PP 有本好書關於 Perl 中的 \s-1OO\s0 是 \*(L"Object\-Oriented Perl\*(R" 作者是 Damian Conway ,出版社爲 Manning Publications, http://www.manning.com/Conway/index.html .Sh "從哪裏可以學習將 Perl 與 C 連接?[h2xs, xsubpp]" .IX Subsection "Where can I learn about linking C with Perl? [h2xs, xsubpp]" 若你要從 Perl程式呼叫 C,就自 perlxstut開始向 perlxs ,xsubpp ,及 perlguts前進。反之,則讀 perlembed ,perlcall ,及 perlguts 。別忘了你可以從各模組的作者如何寫他們的模組及解決他們的問題中學到很多。 .Sh "我已經閱讀了 perlembed,perlguts 等等,但是還是不能在我的 C 程序中嵌入 perl;我作錯了什麼?" .IX Subsection "I've read perlembed, perlguts, etc., but I can't embed perl in my C program; what am I doing wrong?" 自 CPAN 下載 ExtUtils::Embed 套件,然後執行 `make test'。如果測試成功,就一遍又一遍地讀那些 pod 說明檔案。若它失敗了,參看 perlbug並送一份內有 \f(CW\*(C`make test TEST_VERBOSE=1\*(C'\fR 與 \f(CW\*(C`perl \-V\*(C'\fR 輸出的報告。 .Sh "我試着運行我的腳本時,看到了這樣的消息。它是什麼意思?" .IX Subsection "When I tried to run my script, I got this message. What does it mean?" perldiag有一份完整的 perl錯誤與警告訊息列表,並附有說明文字。你也可以用 splain程式 (伴隨 perl而來)去解釋這些錯誤訊息: .PP .Vb 2 \& perl program 2>diag.out \& splain [-v] [-p] diag.out .Ve .PP 更改你的程式讓它替你解釋這些訊息也可以: .PP .Vb 1 \& use diagnostics; .Ve .PP 或 .PP .Vb 1 \& use diagnostics -verbose; .Ve .Sh "什麼是 What's MakeMaker?" .IX Subsection "What's MakeMaker?" 此模組 (亦爲標準 perl 套件之一部份)設計的目的是要替一個模組從一個 Makefile.PL 中自動撰寫出一個 Makefile。詳情請看 ExtUtils::MakeMaker。 .SH "AUTHOR AND COPYRIGHT" .IX Header "AUTHOR AND COPYRIGHT" Copyright (c) 1997\-2002 Tom Christiansen and Nathan Torkington. All rights reserved. .PP This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself. .PP Irrespective of its distribution, all code examples here are in the public domain. You are permitted and encouraged to use this code and any derivatives thereof in your own programs for fun or for profit as you see fit. A simple comment in the code giving credit to the \s-1FAQ\s0 would be courteous but is not required. .SH "譯者" 陳彥銘,蕭百齡,兩隻老虎工作室 .Sh "跋" .br 本頁面中文版由中文 man 手冊頁計劃提供。 .br 中文 man 手冊頁計劃:\fBhttps://github.com/man-pages-zh/manpages-zh\fR