3.3 Perl 的命令列選項

除了用前一節的方式執行 Perl script 之外,還可以利用 Perl 的命令列選項:

[ols3@p4 sample]$ perl -e 'print "Hello Perl !!\n";'
Hello Perl !!

這種方式,主要是利用 -e 選項,將欲執行的述敘放在 '' 單引號之間。

比如,以下方法可以去掉文件中的 ^M 符號:

perl -pi.bak -e 's/\r//g;' index.html

^M 符號的產生,大多是由於 Windows 平台的文件,在上傳檔案至 Linux/Unix平台的過程中,其換行符號沒有做適當的轉換所致。

以下這個命令列選項可以得知 Perl 的版本代碼:

perl -v


This is perl, v5.8.0 built for i386-linux-thread-multi

Copyright 1987-2002, Larry Wall

Perl may be copied only under the terms of either the Artistic License or the
GNU General Public License, which may be found in the Perl 5 source kit.

Complete documentation for Perl, including FAQ lists, should be found on
this system using `man perl' or `perldoc perl'.  If you have access to the
Internet, point your browser at http://www.perl.com/, the Perl Home Page.

由上可知,所用的 Perl 版本是 5.8.0

至於 perl -c 這個選項,在前一節中已提到,可用來檢查 Perl script 語法的正確性:

[ols3@p4 sample]$ perl -c hello.pl
hello.pl syntax OK

Perl 還有非常多的命令列選項,欲知詳情,請下:

[ols3@p4 perl_intro]$ perl -h

Usage: perl [switches] [--] [programfile] [arguments]
  -0[octal]       specify record separator (\0, if no argument)
  -a              autosplit mode with -n or -p (splits $_ into @F)
  -C              enable native wide character system interfaces
  -c              check syntax only (runs BEGIN and CHECK blocks)
  -d[:debugger]   run program under debugger
  -D[number/list] set debugging flags (argument is a bit mask or alphabets)
  -e 'command'    one line of program (several -e's allowed, omit programfile)
  -F/pattern/     split() pattern for -a switch (//'s are optional)
  -i[extension]   edit <> files in place (makes backup if extension supplied)
  -Idirectory     specify @INC/#include directory (several -I's allowed)
  -l[octal]       enable line ending processing, specifies line terminator
  -[mM][-]module  execute `use/no module...' before executing program
  -n              assume 'while (<>) { ... }' loop around program
  -p              assume loop like -n but print line also, like sed
  -P              run program through C preprocessor before compilation
  -s              enable rudimentary parsing for switches after programfile
  -S              look for programfile using PATH environment variable
  -T              enable tainting checks
  -t              enable tainting warnings
  -u              dump core after parsing program
  -U              allow unsafe operations
  -v              print version, subversion (includes VERY IMPORTANT perl info)
  -V[:variable]   print configuration summary (or a single Config.pm variable)
  -w              enable many useful warnings (RECOMMENDED)
  -W              enable all warnings
  -X              disable all warnings
  -x[directory]   strip off text before #!perl line and perhaps cd to director

除了 -e -c -v -h 之外,上述選項中比較常用的還有 -w (打開警告訊息) -T (安全檢查),往後我們會再加以說明。