DOKK / manpages / debian 12 / manpages-zh / perlfaq3.7.zh_CN
PERLFAQ3(7) Perl Programmers Reference Guide PERLFAQ3(7)

perlfaq3 - 编程工具 (2003/11/24 19:55:50)

编程工具和编程支持

我如何作 (任何事)?

你到 CPAN(见 perlfaq2)找过了吗?也许别人已经写了某个模组可以解决你的问题。你查过相关的说明文件了吗 (man pages)?以下是一份概要的索引:

        基础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 技术的大量技巧)

perltoc里有一份粗略的 perl 说明文件组的目录

如何以交互的方式使用 Perl?

典型的作法是使用 perldebug(1)说明文件里提到的 Perl 除虫器,在一个「空的」(译者:即不存在的)程式上执行,像这样:

    perl -de 42

接下来所打入的任意合法 Perl程式码皆会立刻被计算。同时,你可以检查符号表 (symbol table)、取得堆叠的记录 (stack backtraces)、检视变数值、设定阻断点 (set breakpoints) 以及其他符号式除虫器 (symbolic debuggers) 所能作的动作。

有 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/ .

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 CPAN mirror.

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.

怎样查找我的系统中安装了哪些模块?

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 "Perl" (although you can get those with Module::CoreList).

        use ExtUtils::Installed;

        my $inst    = ExtUtils::Installed->new();
        my @modules = $inst->modules();

If you want a list of all of the Perl module filenames, you can use File::Find::Rule.

        use File::Find::Rule;

        my @files = File::Find::Rule->file()->name( '*.pm' )->in( @INC );

If you do not have that module, you can do the same thing with File::Find which is part of the standard library.

    use File::Find;
    my @files;

    find sub { push @files, $File::Find::name if -f _ && /\.pm$/ },
         @INC;

        print join "\n", @files;

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).

        prompt% perldoc Module::Name

You can also try to include the module in a one-liner to see if perl finds it.

        perl -MModule::Name -e1

如何替我的 Perl 程式除虫?

你用过 "use warnings""-w" 吗?它们启用警告模式,来检测不确定的代码。

你用过 "use strict" 吗?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 "my", "our", or "use vars".

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.

  open(FH, "> /etc/cantwrite")
    or die "Couldn't write to /etc/cantwrite: $!\n";

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 awk and C.

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.

如何检测 (profile) 我的 perl 程式?

你该自 CPAN抓取 Devel::DProf 模组,并且使用 perl 标准套件所附的 Benchmark.pm。 Benchmark.pm让你测量程式码的某部份在执行上所花的时间,而 Devel::DProf则详细地替你分析哪一部份的程式用掉多少时间。

Here's a sample use of Benchmark:

  use Benchmark;

  @junk = `cat /etc/motd`;
  $count = 10_000;

  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 },
           });

This is what it prints (on one machine--your results will be dependent on your hardware, operating system, and the load on your machine):

  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)

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.

如何替我的 Perl程式作交叉参考?

B::Xref模组可 以替你的 Perl程式制作 cross-reference报告。用法是:

    perl -MO=Xref[,OPTIONS] scriptname.plx

有 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

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 VI users swear by the following settings in vi and its clones:

    set ai sw=4
    map! ^O {^M}^[O^T

Put that in your .exrc 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

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/ .

有 Perl的 ctags 吗?

Recent versions of ctags do much more than older versions did. EXUBERANT CTAGS is available from http://ctags.sourceforge.net/ and does a good job of making tags files for perl code.

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.

Is there an IDE or Windows Perl Editor?

Perl programs are just plain text, so any editor will do.

If you're on Unix, you already have an IDE--Unix itself. The UNIX philosophy is the philosophy of several small tools that each do one thing and do it well. It's like a carpenter's toolbox.

If you want an IDE, check the following:

ActiveState's cross-platform (as of April 2001 Windows and Linux), multi-language IDE 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 )).
( http://www.castlelink.co.uk/object_system/ ) is a Perl web applications development IDE, apparently for any platform that runs Perl.
( http://open-perl-ide.sourceforge.net/ ) Open Perl IDE is an integrated development environment for writing and debugging Perl scripts with ActiveState's ActivePerl distribution under Windows 95/98/NT/2000.
( http://www.solutionsoft.com/perl.htm ) is an integrated development environment for Windows that supports Perl development.
( http://helpconsulting.net/visiperl/ ) From Help Consulting, for Windows.
( http://www.optiperl.com/ ) is a Windows IDE with simulated CGI environment, including debugger and syntax highlighting editor.

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.

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 "Text Only". 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.

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.

http://www.gnu.org/software/emacs/windows/ntemacs.html
http://www.microemacs.de/
http://www.xemacs.org/Download/index.html
http://space.mit.edu/~davis/jed/

or a vi clone such as

ftp://ftp.cs.pdx.edu/pub/elvis/ http://www.fh-wedel.de/elvis/
http://dickey.his.com/vile/vile.html
http://www.vim.org/

For vi lovers in general, Windows or elsewhere:

        http://www.thomer.com/thomer/vi/vi.html

nvi ( http://www.bostic.com/vi/ , available from CPAN in src/misc/) is yet another vi clone, unfortunately not available for Windows, but in UNIX 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.

The following are Win32 multilanguage editor/IDESs that support Perl:

http://www.starbase.com/
http://www.MultiEdit.com/
http://www.slickedit.com/

There is also a toyedit Text widget based editor written in Perl that is distributed with the Tk module on CPAN. 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 IDE for Perl/Tk GUI creation.

In addition to an editor/IDE you might be interested in a more powerful shell environment for Win32. Your options include

from the Cygwin package ( http://sources.redhat.com/cygwin/ )
from the MKS Toolkit ( http://www.mks.com/ ), or the Bourne shell of the U/WIN environment ( http://www.research.att.com/sw/tools/uwin/ )
ftp://ftp.astron.com/pub/tcsh/ , see also http://www.primate.wisc.edu/software/csh-tcsh-book/
ftp://ftp.blarg.net/users/amol/zsh/ , see also http://www.zsh.org/

MKS and U/WIN are commercial (U/WIN is free for educational and research purposes), Cygwin is covered by the GNU Public License (but that shouldn't matter for Perl use). The Cygwin, MKS, and U/WIN all contain (in addition to the shells) a comprehensive set of standard UNIX toolkit utilities.

If you're transferring text files between Unix and Windows using FTP be sure to transfer them in ASCII mode so the ends of lines are appropriately converted.

On Mac OS the MacPerl Application comes with a simple 32k text editor that behaves like a rudimentary IDE. In contrast to the MacPerl Application the MPW Perl tool can make use of the MPW Shell itself as an editor (with no 32k limit).

are text editors for Mac OS that have a Perl sensitivity mode ( http://web.barebones.com/ ).
is an editor, written and extensible in Tcl, that nonetheless has built in support for several popular markup and programming languages including Perl and HTML ( http://alpha.olm.net/ ).

Pepper and Pe are programming language sensitive text editors for Mac OS X and BeOS respectively ( http://www.hekkelman.com/ ).

哪儿有 vi 用的 Perl 宏?

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/ .

给 emacs用的 perl模式又要去哪抓呢?

从大约 Emacs 19.22版 (version 19 patchlevel 22)起,已内含了 perl-mode.el及 perl 除虫器的支援。它们应该会和标准的 Emacs 19版一起出货。

在 perl原始码的目录下,你会找到一个叫作 ``emacs'' 的目录,里面包括一个 cperl-mode 可以把程式中的关键字上色、提供内文相关的协助以及其它方便的功能。

注意:``main'foo''(其中的单引号)会让 emacs的 perl-mode 出问题,并且会弄乱内 缩 (indentation) 与高亮 (hilighting)。不过你本来就该用 ``main::foo''的 (译者按: main'foo 是表示模组或 package的旧式写法;新式的 [perl5的]写法是 main::foo)。

如何在 Perl里使用 curses?

The Curses module from CPAN 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 rep ps axu similar to top.

X或 Tk如何与 Perl配合呢?

Tk 模块是一个完全以 Perl 为基础,面向对象的接口,让你不用学 Tcl也可以使用 Tk工具组。Sx则是 Athena Widget set专用的介面。两者都可在 CPAN取得。参见分类 http://www.cpan.org/modules/by-category/08_User_Interfaces/

Invaluable for Perl/Tk programming are the Perl/Tk FAQ 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 .

如何不靠 CGI或 Tk 帮助作出简单的目录(选单)?

http://www.cpan.org/authors/id/SKUNZ/perlmenu.v4.0.tar.gz 是个以 curses为基础的模组,可以达成你的要求。

如何让我的 Perl程式跑得更快些?

最好是能设计一个较好的演算法 (algorithm),这通常会让程式有大不相同的表现。Jon Bentley's book Programming Pearls (没有拼写错误!) 中有些你或许想知道的增进效率小技巧。 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.

其它方法包括自动载入较少使用的 Perl 程式码。请参看标准 perl 套件中的 AutoSplit及 AutoLoader模组的用法。或当你能断定程式执行效率的瓶颈在何处时,用 C来写那个部份,就像用组合语言来撰写 C程式的瓶颈部份一样。与此法相近的是使用以 C撰写瓶 颈部份的模组 (例如 CPAN中的 PDL 模组)。

如果你目前是将你的 perl直译器动态连结到 libc.so的话,重新作一份静态连结到 libc.a的 perl直译器可以提高 10-25%的执行效能。虽然这会使你的 perl直译器变得更胖,但你的 Perl程式 (及程式设计者) 或许会因此而感谢你。详情请参考 perl标准套件原始码版本中的 INSTALL 档案。

使用 undump程式把编译后的档案格式存到硬碟里以加快执行的速度已经是老掉牙的手法了。它已不再是个可行的方法,因为这方法只有几种平台能用,况且它终究不是个治本之 道。

如何让我的 Perl 程序少用一些内存?

当问题变成时间与空间的交易时, Perl 几乎总是用记忆体来帮忙解决问题。 Perl中的纯量 (Scalar) 耗掉的记忆体比 C中的字串形态还多,阵列又更多, 更别谈杂凑阵列了 (Hashes)。关于这一点,我们当然还有很多工作得作,近来发布的版本,已开始针对这些问题做改进了。例如, 5.004 版中, 重复的散列键 (duplicate hash keys) 由使用它的杂凑阵列共用,这样就不用再重新定份位置给它了。

在某些情况下,使用 substr()或 vec()来模拟数组有很大的好处。例如,一个有上千 个布林代数值的阵列将占用至少 20,000位元组的空间,但是它可以被转变为一个 125位元组的位元向量 (bit vector)以节省相当可观的记忆体。标准套件中的 Tie::SubstrHash模组也能够帮助特定形态的资料结构节省些记忆体。若你正在和一些特殊的资料结构奋战 (例如,矩阵),用 C写的模组所耗掉的记忆体可能低于同功能并用 Perl写的模组。

另一件值得一试的是,查一下你的 Perl是以系统内的 malloc 还是 Perl内含的 malloc 编译起来的。不论是哪个,试着换成另一个,再看看这是否造成任何差别。关于 malloc的资讯可在 perl标准套件原始码版中的 INSTALL 档案找到。键入 "perl -V:usemymalloc". 就可以知道你是否在使用 perl的 malloc。

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:

* 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:

        #
        # Good Idea
        #
        while (<FILE>) {
           # ...
        }
    

instead of this:

        #
        # Bad Idea
        #
        @data = <FILE>;
        foreach (@data) {
            # ...
        }
    

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.

* Use map and grep selectively
Remember that both map and grep expect a LIST argument, so doing this:

        @wanted = grep {/pattern/} <FILE>;
    

will cause the entire file to be slurped. For large files, it's better to loop:

        while (<FILE>) {
                push(@wanted, $_) if /pattern/;
        }
    
* Avoid unnecessary quotes and stringification
Don't quote large strings unless absolutely necessary:

        my $copy = "$large_string";
    

makes 2 copies of $large_string (one for $copy and another for the quotes), whereas

        my $copy = $large_string;
    

only makes one copy.

Ditto for stringifying large arrays:

        {
                local $, = "\n";
                print @big_array;
        }
    

is much more memory-efficient than either

        print join "\n", @big_array;
    

or

        {
                local $" = "\n";
                print "@big_array";
        }
    
* 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.
* Tie large variables to disk.
For "big" data stores (i.e. ones that exceed available memory) consider using one of the DB modules to store it on disk instead of in RAM. This will incur a penalty in access time, but that's probably better than causing your hard disk to thrash due to massive swapping.

把局部变量的引用返回是不安全的做法吗?

这样是安全的,Perl的资源回收 (garbage collection)系统会解决此问题。

    sub makeone {
        my @a = ( 1 .. 10 );
        return \@a;
    }

    for ( 1 .. 10 ) {
        push @many, makeone();
    }

    print $many[4][5], "\n";

    print "@many\n";

我如何释放一个数组或散列以缩小我的程式尺寸?

你无法这么作。系统配置给程式的记忆体是覆水难收。这也是为何执行很长一段时间的程式有时会重新执行 (re-exec)它们自己的原因。 Some operating systems (notably, systems that use mmap(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 OS's malloc, not perl's.

然而,在使用你的变数时,明智地用 my()来定义执行范围,可让 Perl在脱离该范围后 将它们所占的空间释放给其它部份的程式。 (注:my()的变数也比全域变数执行起来快 10%。)当然,一个全域变数永远没有超出范围的时候,所以你无法将它占用的空间自动重新分配,不过,把它 undef() 或/和 delete()会有相同的效果。总之,在 Perl里,你并不能/应该去担心太多有关记忆体定址与解除这件事,而我们连添加这项功能(资料形态的预先定址),目前都已在进行中。

如何让我的 CGI脚本 (script)执行起来更有效率?

除了使一般 Perl程式加快或缩小的平常手段外,一个 CGI 程式还有其他的顾虑。也许它每秒会被执行好几次。每次它执行时,重新编译所花的时间、加上定址所需的 1 MB以上的系统记忆体,就是一个大杀手。光是编译成 C 是没啥帮助的 ,因为瓶颈在于整个程序开始时所负担的包袱 (start-up overhead) 。

最起码有两种较流行的方法可以避免这些包袱。一种解法是将 mod_perl 或是 mod_fastcgi其中一个模组加在你所执行的 Apache HTTP server。

有了 mod_perl 和 Apache::*模组 (从 CPAN取得),httpd执行时会带起一个内 嵌的 Perl直译器,而它会预先编译你的程式,并在不产生其它子程序的情况下用同一个定址空间来执行。Apache 扩充模组亦给 Perl一个连通 server API 的管道,所以用 Perl写的模组可以做到任何 C写的模组所具备的功能。详情请参阅 http://perl.apache.org/

而有了 FCGI模组 (自 CPAN取得) 和 mod_fastcgi 模块(从 http://www.fastcgi.com/取得),每个 Perl 程序将成为一个永久的 CGI 守护进程。

这些方法对你的系统与你撰写 CGI程式的方法都有超乎想像之外的影响,所以请小心地使用它们。

参见 http://www.cpan.org/modules/by-category/15_World_Wide_Web_HTML_HTTP_CGI/ .

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 CGI Perl when running in persistent Perl mode or 4 to 5 times faster without any modification to your existing CGI programs. Fully functional evaluation copies are available from the web site.

如何隐藏 Perl程式的原始码?

删除它。 :-) 说真的,有一些具有不同“安全”等级的方法(大部分都不能令人满意)。

首先,你 不能拿走读取权,不然你的程式怎么被解译或是编译呢? (不过那也并不表示一个 CGI程式的原始码可以被使用者读取。)所以你得让档案权限停留在 0755这个友善的阶段。

有些人认为这是个安全上的漏洞。不过若你的程式作的是不安全的事情,光仰赖别人看不见这些漏洞、不知从何下手,那么它依然是不安全的。其实对有些人来说他们并不需要看见程式原始码便可能判定并揭露这些不安全的部份。透过隐瞒达到的安全,就是不修正臭虫反而隐藏它们,实际上是没有安全性可言的。

你可以试着透过原始码过滤模组 (CPAN中的 Filter::*)来替原始码加密。但高手也许有办法将其解密还原。你也可以用下面提到的 byte code 编译器与直译器,但高手也有可能反解译它。你可以试试后面提到的原生码编译器 (native-code compiler),但高手也有可能反组译它。这些手段都需要不同难度的技巧才能让别人拿到你的原始码,但没有一种能够很确定地隐藏它。(这对每种语言来说都为真,不是只有 Perl)

很容易从 Perl 程序中恢复出源码。只要将程序作为 perl 解释器的参数,并且使用 B:: 中的模块就可以了。B::Deparse 模块足以恢复大多数隐藏的代码。再次的,这不是 Perl 特有的东西。

如果你所担心的是别人自你的程式码中获利,那么一纸权限执照是能提供你法律上安全的唯一途径。注册你的软体并且写份权限说明,再加上一些具威胁性的句子像“这是 XYZ公司未出版的专有软体。你能撷取它并不代表你具有使用的权限...”之类云云。当然,我们不是律师,所以若你想要你的执照中每一句话在法庭上都站得住脚,就去见个律师吧。

如何把我的 Perl程式码编译成 byte code或 C?

Malcolm Beattie已经写了一个多功能的后端编译器,可以从 CPAN取得,它就能做到这两项功能。它包含在 perl5.005 发布中,但是仍然是测试版。这代表着若你是个程式设计 员而非寻找万灵解药的人,那么参与其测试就会充满趣味。

请了解光是编译成 C 其本身或在本质上并不能保证它就会跑得快更多。那是因为除了在运气好的状况中有一堆可以衍生成出来的原生形态外,平时的 Perl 执行系统环境依然存在因此依然会花差不多长的执行时间与占用差不多大小的记忆空间。大多数程式能省下来的不过是编译时间,这使执行速度顶多快 10-30%。有些罕见的程式能真正从中受利 (例如增快好几倍),但这还得配合原始码的微调。

你或许会惊讶地发现,现行版本的编译器做出来的执行档大小跟你的 Perl直译器一样大,有时更大些。那是因为依照现在的写法,所有的程式皆转成一个被 eval()的大叙述。只要建造一个动态连结的 libperl.so程式库,并将之连结起来,你就可以戏剧性地减少这 种浪费。参看 perl原始码套件中的 INSTALL pod档案以获得更详尽的讯息。如果你用这方法连结你主要的 perl执行档,就能使它变得很渺小。举例来说,在作者之一的系 统里, /usr/bin/perl只有 11k“小”而已!

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 VM 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 libperl.so), you'll probably want a complete Perl install anyway.

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/ .

Perl 5.6 comes with Java Perl Lingo, or JPL. JPL, still in development, allows Perl code to be called from Java. See jpl/README in the Perl source tree.

如何才能让

OS/2下只要用:

    extproc perl -S -your_switches

当作 "*.cmd" 档案的第一行 ("-S" 是因 cmd.exe中其 `extproc'处理的臭虫才要的)。DOS使用者应先制作一个相对的 batch 档案然后将它以 ALTERNATIVE_SHEBANG 的方式写成程式。(更多讯息在原始码版本的 INSTALL档案里)

The Win95/NT installation, when using the ActiveState port of Perl, will modify the Registry to associate the ".pl" 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 ".pl" with the interpreter, NT people can use: "SET PATHEXT=%PATHEXT%;.PL" to let them run the program "install-linux.pl" merely by typing "install-linux".

麦金塔的 perl程式将会有适当的创造者与形态 (Creator and Type),所以双击它们就会执行这些 perl 应用程式。

重要:不论你做什么,请千万不要因为觉得沮丧,就把 perl 直译器丢到你的 cgi-bin目录下,好让你的 web 伺服器能执行你的程式。这是一个非常大的安全漏洞。花点时间想想怎样才是正确的做法吧。

我能利用命令行写出有用的程式吗?

可以。详情请看 perlrun。以下有些范例 (假设用的是标准的 Unix shell引言规则)。

    # 把第一栏和最后一栏相加
    perl -lane 'print $F[0] + $F[-1]' *

    # 辨别是否为文字档
    perl -le 'for(@ARGV) {print if -f && -T _}' *

    # 移除 C程式中的说明
    perl -0777 -pe 's{/\*.*?\*/}{}gs' foo.c

    # 让档案年轻一个月,躲避 reaper daemons
    perl -e '$X=24*60*60; utime(time(),time() + 30 * $X,@ARGV)' *

    # 找出第一个未用的 uid
    perl -le '$i++ while getpwuid($i); print $i'

    # 显示合理的使用说明路径 (manpath)
    echo $PATH ⎪ perl -nl -072 -e '
        s![^/+]*$!man!&&-d&&!$s{$_}++&&push@m,$_;END{print"@m"}'

好吧,最后一个例子事实上是「perl程式困惑化」竞赛 (Obfuscated Perl)的 参赛作品。 :-)

为何一行的 perl 程式无法在我的 DOS/Mac/VMS系统上运作?

问题通常出在那些系统的命令解译器对于参数的引用与 Unix shells 所作的解释不同,而后者很不幸的是这些一行 perl 的生父。在某些系统,也许你得把单引号改成双引号,但这却是你万万 不可在 Unix或 Plan9系统上作的事。你也许还得把一个 %改成 %%。

例如:

    # Unix
    perl -e 'print "Hello world\n"'

    # DOS 和其他机器
    perl -e "print \"Hello world\n\""

    # Mac
    print "Hello world\n"
     (然后运行 "Myscript" 或按 Shift-Command-R)

    # MPW
    perl -e 'print "Hello world\n"'

    # VMS
    perl -e "print ""Hello world\n"""

问题是,这些方法没有一个是完全可靠的:它都得看命令解译器的脸色。在 Unix中,前两者通常可以用。在 DOS下,两者可能都没有用。若 4DOS是命令解译器,下面此法可能比 较有希望:

  perl -e "print <Ctrl-x>"Hello world\n<Ctrl-x>""

在 Mac 下,端视你所用的环境为何。 MacPerl所附的 shell,或是 MPW, 其所支援的参数格式有不少都蛮像 Unix shells的,除了它自在地使用 Mac 的非 ASCII字元当成控制字元。

Using qq(), q(), and qx(), instead of "double quotes", 'single quotes', and `backticks`, may make one-liners easier to write.

恐怕我得说这问题并没有一般解。白话一点说,它真是一团乱。

[部份答案是由 Kenneth Albanowski 所提供的。]

我得去哪里学 Perl的 CGI或是 Web程式设计呢?

就模组来说,去 CPAN抓 CGI 和 LWP 两个模组。就书本来看,参考关于书那部份里特别和 web 相关的问题。若有与 web相关的疑难杂症,像“为何我收到 500错误”或“它在命令列模式下跑得好好的,怎么不能在浏览器下正常执行”时,请参看:

        http://www.perl.org/CGI_MetaFAQ.html

从哪里可以学习面向对象的 Perl 编程?

perltoot是个好开始,然后你可以再参考 perlobj 和 perlboot,Perltoot,perltooc 以及 perlbot (如果你使用老版本的 Perl,你可能没有这些。去 http://www.perldoc.com/ 下载吧,但是首先考虑一下升级你的 perl)

有本好书关于 Perl 中的 OO 是 "Object-Oriented Perl" 作者是 Damian Conway ,出版社为 Manning Publications, http://www.manning.com/Conway/index.html

从哪里可以学习将 Perl 与 C 连接?[h2xs, xsubpp]

若你要从 Perl程式呼叫 C,就自 perlxstut开始向 perlxs ,xsubpp ,及 perlguts前进。反之,则读 perlembed ,perlcall ,及 perlguts 。别忘了你可以从各模组的作者如何写他们的模组及解决他们的问题中学到很多。

我已经阅读了 perlembed,perlguts 等等,但是还是不能在我的 C 程序中嵌入 perl;我作错了什么?

自 CPAN 下载 ExtUtils::Embed 套件,然后执行 `make test'。如果测试成功,就一遍又一遍地读那些 pod 说明档案。若它失败了,参看 perlbug并送一份内有 "make test TEST_VERBOSE=1""perl -V" 输出的报告。

我试着运行我的脚本时,看到了这样的消息。它是什么意思?

perldiag有一份完整的 perl错误与警告讯息列表,并附有说明文字。你也可以用 splain程式 (伴随 perl而来)去解释这些错误讯息:

    perl program 2>diag.out
    splain [-v] [-p] diag.out

更改你的程式让它替你解释这些讯息也可以:

    use diagnostics;

    use diagnostics -verbose;

什么是 What's MakeMaker?

此模组 (亦为标准 perl 套件之一部份)设计的目的是要替一个模组从一个 Makefile.PL 中自动撰写出一个 Makefile。详情请看 ExtUtils::MakeMaker。

Copyright (c) 1997-2002 Tom Christiansen and Nathan Torkington. All rights reserved.

This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself.

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 FAQ would be courteous but is not required.

译者

陈彦铭,萧百龄,两只老虎工作室

本页面中文版由中文 man 手册页计划提供。
中文 man 手册页计划:https://github.com/man-pages-zh/manpages-zh

2003-11-25 perl v5.8.3