Scroll to navigation

PERLFAQ3(7) Perl Programmers Reference Guide PERLFAQ3(7)

NAME

perlfaq3 - 程式設計工具 (2003/11/24 19:55:50)

DESCRIPTION 描述

程式設計工具和程式設計支援

我如何作 (任何事)?

你到 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。

AUTHOR AND COPYRIGHT

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