Perl基本语法介绍
2009-12-01 14:01:19 阿炯

前言:这篇文章是花了我很多时间、费了我很多心血才完成的,虽然连我自己都觉得无法达到尽善尽美的境界,但希望能帮助大家入门,稍微了解到Perl 到底是个什么样的东西,Perl到底有那些强大的功能,那么这篇文章的目的就达到了。我分做数据型态、控制叙述、子程序、I/O和档案处理、Regular Expressions、Spectial Variables、Help、函数、总结这几部分来讲解,但只是叙述了一些Perl的基本语法而已,Perl活泼的特性和程序的技巧就无法一一详述了,甚为缺憾。

(1) 数据型态(Data type):
Perl 的数据型态大致分为四种:Scalar、Scalar Array、Hash Array、References,看起来虽少但用起来却绰绰有余。尤其在写Perl程序时可以不必事先宣告变量,这一点对刚学程序语言的人甚为方便,不过为了以后程序除错和维护方便,我建议你还是养成事先宣告变量的习惯比较好。

(a) Scalar:
纯量变量是Perl里最基本的一种数据型态,它可以代表一个字符、字符串、整数、甚至浮点数,而Perl把它们都看成是一样的东东! 你甚至可以混着用,不可思议吧。例如:
# 井字号开头的后面都是批注。
# 纯量变数以$开头。
# my 是一种宣告变量的方式,它可以使变量区域化。
# 宣告变量时若不加 my 或 local 则Perl会把它当作全域变量使用。
# 习惯上,我们会将字符串用双引号括起来,而数值就不用加引号。
my $x="abc";
my $x=123;
my $x=4.56;

那么程序怎么判断这是数值还是字符串呢? 其实不是程序判断,而是你自己要判断。Perl分别提供了一堆运算子来处理数字和字符串,你必须知道这个变量是数值或字符串,才能使用个别的运算子来对变量做运算。我分别列出字符串运算子和数值运算子,好让大家能区分它们的不同。

◎字符串运算符
String Operator    Purpose
x    Returns a string consisting of the string on the left of the operand, repeated the number of times of the right operand.

.    Concatenates the two strings on both sides of the operator.

eq    Returns True if the two operands are equivalent, False otherwise.

ne    Returns True if the two operands are not equal, False otherwise.

le    Returns True if the operand on the left is stringwise less than the operand on the right of the operator. Returns False otherwise.

lt    Returns True if the operand on the left is stringwise less than or equal to the operand on the right of the operator. Returns False otherwise.

ge    Returns True if the operand on the left is stringwise greater than or equal to the operand on the right of the operator. Returns False otherwise.

gt    Returns True if the operand on the left is stringwise greater than the operand on the right of the operator. Returns False otherwise.

cmp    Returns -1, 0, or 1 if the left operand is stringwise less than, equal to, or greater than the right operand.

,    Evaluates the left operand, the evaluates the right operand. It returns the result of the right operand.

++    Increments the string by one alphabetic value.

◎数值运算符
Value Operator    Purpose
+    Computes the additive value of the two operands.

-    Computes the difference between the two operands.

*    Computes the multiplication of the two operands.

/    Computes the division between the two operands.

%    Computes the modulus(remainder) of the two operands.

= =    Returns Ture if the two operands are equivalent, False otherwise.

!=    Returns Ture if the two operands are not equal, False otherwise.

<=    Returns Ture if the operand on the left is numerically less than or equal to the operand on the right of the operator. Returns False otherwise.

=>    Returns Ture if the operand on the left is numerically greater than or equal to the operand on the right of the operator. Returns False otherwise.

<    Returns Ture if the operand on the left is numerically less than the operand on the right of the operator. Returns False otherwise.

>    Returns Ture if the operand on the left is numerically greater than the operand on the right of the operator. Returns False otherwise.

Returns -1 if the left operand is less than the right, +1 if is it greater than, and 0(False) otherwise.
&&    Performs a logical AND operation. If the left operand is True m then the right operator is not evaluated.

||    Performs a logical OR operation. If the left operand is True m then the right operator is not evaluated.

&    Returns the valueof the two operators bitwise ANDed.

|    Returns the valueof the two operators bitwise Ored.

^    Returns the valueof the two operators bitwise XORed.

++    Increment operator. Increments the variable's value by 1.

--    Decrement operator. Decrements the variable's value by 1.

**    Computes the power of the left-hand value to the power of the rihght-hand value.

+=    Adds the value of the right-hand operand to the value of the left-hand operand.

-+    Subtracts the value of the right-hand operand to the value of the left-hand operand.

*=    Mlutiplies the value of the left-hand operand to the value of the right-hand operand.

>>    Shifts the left operand right by the number of bits that is specified by the right operand.

<<    Shifts the left operand left by the number of bits that is specified by the right operand.

~    Performs a 1s complement of the operator. This is a unary operator.

(b) Scalar Array:
纯量数组,数组内的每一个元素都是Scalar variable。宣告及使用方式如下:
# 纯量数组以 @ 开头。
my @array;
my @array=qw(a b c d);

# qw 函数会将其后的每个元素用逗点隔开,效果就像下面这行。
my @array=("a","b","c","d");

# 当然你也可以一个个元素宣告,下面就是存取每一个元素的方法。
# 因为数组中的每一个元素都是纯量变量,所以要以 $ 开头,
# 刚开始容易搞混,请注意。
$array[0]="a"; $array[1]="b"; $array[2]="c"; $array[3]="d";

# 使用for loop印出数组内每个元素的值。
for($i=0; $i<=$#array; $i++) {
print "$array[$i]\n";
}

看到$#array这个奇怪的东东没? 这是Perl的一个特殊用法,代表这个数组最后一个元素的注标。由于Perl不必事先宣告变量,也不必预先宣告数组的大小,甚至可以随时增加新元素,那我们怎么知道这个数组到底有多大呢? 透过这个特殊变量我们可以得知这个这个数组最后一个元素的注标,自然而然也就知道这个数组究竟有多大了。另外Perl只定义了一维数组的语法,二维以上只能用指标间接来达成。

(c) Hash Array(Associative Array):
杂凑数组也叫做相关数组,它和一般数组没什么不同,差别只是在它的索引值用的是字符串,而非一般数组所用的整数值,因此相关数组不像一般数组一样有次序的概念,它没有所谓的第一项数据这种说法。它就相当于把一堆变量组合成一个group,然后我们可以透过索引字符串存取这个group每一个元素的值。相关数组的宣告及使用方式如下:

# 相关数组是以%符号开头的。
my %hash;

# => 这个符号是Perl5新增的,是为了相关数组量身定做的,
# 因为索引和元素值都是纯量,若使用 => 这个符号,
# (索引=>元素值) 两两对应,就不容易发生失误。
my %hash=("i1"=>"aaa","i2"=>"bbb","i3"=>"ccc");

# 上面这行的效果和下面这行是一样的。
my %hash=("i1","aaa","i2","bbb","i3","ccc");

# 下面是存取每个元素的方法,注意是用大括号把索引括起来哦。
# 习惯上索引值用单引号、元素值用双引号括起来。
$hash{'i1'}="aaa"; $hash{'i2'}="bbb"; $hash{'i3'}="ccc";

# 下面是使用相关数组的三个例子:
foreach $key (keys %hash){
print "$hash{$key}\n";
}
foreach $value (values %hash)
while(($key,$value)=each %hash)

Perl有上述三个函数可对相关数组做运算:keys函数可取出相关变量的索引值,组成一纯量数组,注意这些由keys函数取出的索引值没有次序性;values函数可取出相关变量的元素值;each函数则会取出(索引、元素)对。使用者可视情况而用。

(d) References(Pointer):
Perl 5新增了参考指针的数据型态,使Perl和C一样可借由指针建立一些复杂的数据结构。普通程序是用不到指针这玩意的,下面也只是简单介绍一下,看不懂的人可不必深究。

⊙如何取得变量的地址?
$scalarRef=\$scalarVar;
$arrayRef=\@arrayVar;
$hashRef=\%hashVar;
$funcRef=\&funcName;

⊙如何使用指针?
print $$scalarRef;
print "@$arrayRef";
print $hashRef->{$key};
&$funcRef;

⊙Anonymous Array References:(二维数组)
$arrayRef=[[1,2,3,4],a,b,[x,y,z],c];
print "$arrayRef->[0][0]\t$arrayRef->[2]\t$arrayRef->[3][2]\n";

⊙Anonymous Hash References:
$hashRef={a=>aa,b=>bb,c=>cc};
print "$hashRef->{a}\t$hashRef->{b}\t$hashRef->{c}\n";

(2) 控制叙述(Control Statements)
(a) Conditional Control Statements:
Perl的条件控制叙述和C语言很像,让使用者很快就能掌握它。不过Perl比C语言又另外多了些实用的语法,我用底线标出来,大家一看便知。

# Expression 就是条件叙述式,Perl和C一样没有定义布尔数据型态(Boolean data type),
# 因此 0 是false、非0 是ture。另外要注意字符串运算子和数值运算子要分清楚哦。
# Code Segment 就是用大括号括起来的一堆指令,也就是一个Block。
if (Expression) {Code Segment}

if (Expression) {Code Segment} else {Code Segment}

if (Expression) {Code Segment} elsif (Expression) {Code Segment} else {Code Segment}
# elsif 就是 else if

# 如果指令(statement)只有一项,我们可以使用倒装句法,看起来比较简洁。
statement if (Expression);

# unless 就是if not
statement unless (Expression);
例:
print "HELLO!\n" if ($name eq "friend");
$x-=10 if ($x == 100);

看吧! C 语言有的Perl大部分都有,学过 C 的人可以毫不费力的学会Perl。

(b) Loop Control Statements:
Perl的循环控制叙述也和C语言很像,当然,照例Perl也另外多了些实用的语法:
# 注意:纯量变数前面要加个 $ 字号,这一点和C语言不一样哦。

for($i=0; $i<=10; $i++) {Code Segment}
# foreach 是承袭UNIX的shell script来的,
# 第一个自变量是纯量变数,第二个自变量要用括号括起来,里面是一个纯量数组,
# 顾名思义它就是把数组中的每个元素依序传给第一个自变量,直到全部传完。
# 它和 for($i=0; $i<=$#array; $i++) 用法虽然不同,但目的都是要取出数组的每个元素。
foreach $i (@array) {Code Segment}

# 其实在Perl中,for和foreach是可以混着用的,就看个的人习惯了。
# 下面这行就等于上面第一个叙述,不过简洁多了,大家可以试着用用看。
for $i (0..10) {Code Segment}

# while控制循环和后置循环。
while($i<=10) {Code Segment}
do {Code Segment} while(Expression);

# Perl也有和C语言的break和continue一样的指令,Perl叫它做 last 和 next (较口语化)。
# last是跳出现在所在的循环,next则是跳过下面的指令直接执行下一次的循环。
while(chomp($i=)){
next if ($i == 5);
last unless ($i > 10);
}

Perl 还有提供label(标记)的语法,也就是goto 指令,不过有经验的programer并不喜欢用它,我也不建议大家使用,所以就此按下不讲。有兴趣的人请自行查阅。还有一点值得注意的是Perl没有提供像C语言一样的 switch 叙述,不过Perl的pattern match的功能非常强,所以我建议你直接用 if else 叙述来做就好了。

(3) 子程序(Subroutines)
(a) Syntax: sub NAME {Code}

(b) 呼叫子程序: &NAME(para1, para2,...)

(c) 参数传递:@_
Perl 和C一样是采用Call by value的方式,不过因为Perl不用事先宣告变量,所以建立子程序的时候也不用宣告要传递什么参数。当主程序在传递参数给子程序时,Perl会把括号括起来的参数按顺序放在一个特殊的全域变量 @_ 数组中,然后子程序就可以随意使用数组 @_ 里的参数,例如 $_[0] 是第一个参数, $_[1] 是第二个,或是用 my ($a1,$a2,$a3,...) = @_;来取出各个参数,当然 my @arg=@_; 或 my %arg=@_; 也是可以的。由于Perl的语法非常活泼,使得程序在维护时特别棘手,因此写批注成为一项很重要的工作。我建议你最好在每个子程序前面加上对这段子程序的描述,特别是需要传递的参数要注明清楚。

(d) Variable Localization:my or local
通常我们在程序中定义的变量都是全域变量,所以在子程序中若要把变量区域化则要加上 my 或 local 关键词,例如:my $x=3;,若子程序所用的变量名不小心和主程相同,Perl会以目前正在执行的子程序里的变量为优先。

(4) I/O和档案处理
(a) Syntax:
open(FILEHANDLE,"Expression");
close(FILEHANDLE);
这里的Expression是一个叙述加上文件名称,若Expression只有文件名称没有加上叙述,则预设是只读。Expressions叙述如下:

Expression    Effect
open(FH, "
open(FH, "+
open(FH, ">filename") #Opens filename for writing.

open(FH, "+>filename") #Opens filename for both reading and writing.

open(FH, ">>filename") #Appends to filename.

open(FH, "command|") #Runs the command and pipes its output to the filehandle.

open(FH, "command|") #Pipes the output along the filehandle to the command.

open(FH, "-") #Opens STDIN.

open(FH, ">-") #Opens STDOUT.

open(FH, "<&=N") #Where N is a number, this performs the equivalent of C's fdopen for reading.

open(FH, ">&=N") #Where N is a number, this performs the equivalent of C's fdopen for writing.

示例:
# 开启$filename这个档案,若开启失败则印出die后面的讯息,并结束程序。
open(FILE, $filename) || die "Can't open file $filename : $!\n";

# 下面是一个十分精简的写法,和 while($_=){print "$_";} 是等效的。
print while();

# 档案开启后要记得随手关闭,这才是写程序的好习惯。
close(FILE);

# $!和$_都是Perl的特殊变数,下面会介绍的。

(b) Input:
Perl没有特别用来输入的函数,因为Perl在执行程序时,会自动开启标准输入装置,其filehandle定为STDIN,所以在Perl中要输入数据的方法就是使用:

# Perl不会自动去掉结尾的CR/LF,跟C语言不同,所以要用chomp函数帮你去掉它。
# 大家常常会忘记这个动作,导致结果跟你想的不一样,要特别注意一下。
$input=<>; chomp $input;
# 下面是较简洁的写法。
chomp($input=<>);

(c) Output:print "variables or 字符串";
Perl也有printf()函数,语法和C语言一模一样,我就不多做介绍了。Perl另外有个print函数,比printf()更方便、更好用,包你爱不释手。Output不外乎是输出到屏幕或档案,用例子来说明比较容易了解。

# 不用再指定变量的data type,这样不是比printf()方便多了吗?
print "Scalar value is $x\n";

# . 是字符串加法的运算子,上下这两行是等效的。
print
"Scalar value is " . $x . "\n";

# 输出到档案的方法。
print FILE "print $x to a file.";

# 下面是print的特殊用法,学自shell script的用法:
print<

这招叫做 here document,XXX可以是你取的任何标识符,在标识符之间的字都会按照你所写的样子输出,就像\标签一样。而当一行的开头是XXX你取的这个标识符时,才会停止输出。
XXX

Perl 也有和 C 一样以 "\" 开头的特殊字符:
\t    tab
\n    newline
\r    return
\f    form feed
\b    backspace
\a    alarm(bell)
\e    escape
\033  octalchar
\x1b  hex char
\c[   control char
\l    lowercase next char
\u    uppercase next char
\L    lowercase till \E
\U    uppercase till \E
\E    end case modification
\Q    quoteregexp metacharacters till \E

另外需要说明的是 Perl 融合了unix shell script的使用惯例,以双引号("")括起来的字符串会先经过展开,但反斜线(\)后面的字符则不展开,当作一般字符看待。而以单引号('')括起来的字符串完全不会展开,以反单引号(``)括起来的字符串会把它当作命令列指令一样执行,等于system()一样。初学者常常会搞混,但习惯之后就会觉得不这样分清楚反而不行哩,举个例吧:
$x="ls -l";
print "$x"; # Output ls -l
print "\$x"; # Output $x
print '$x'; # Output $x
print `$x`; # Output files in this directory

(5) Regular Expressions
Regular Expression通常是用来寻找特定的字符串样式(pattern),也就是所谓格式辨认(pattern-matching)的功能。它的运算子是『=~』和『!~』,可以把它念做match和not match。

Syntax: $string =~ /regular expression/expression modifier

例:$sentence =~ /Hello/

(a) Modifiers:修饰选项可有可无,它是用来对整个叙述作修正的。
g     Match globally, i.e. find all occurrences.

i     Makes the search case-insensitive.

m     If the string has new-line characters embedded within it, the metacharacters ^ and $ will not work correctly. This modifier tells Perl to treat this line as a multiple line.

o     Only compile pattern once.

s     The character . matches any character except a new line. This modifier treats this line as a single line, which allows . to match a new-line character.

x     Allows white space in the expression.

(b) Metacharacter:下面这些字符都具有特殊意义,可以让你建立更复杂的搜寻样式(searching pattern)。
\    Tells Perl to accept the following characters as a regular character; this removes special meanings from any metacharacter.

^     Matches the beginning of the string, unless /m is used.
.     Matches any character except a new line character, unless /s is used.

$     Matches the end of the string, unless /m is used.

|     Expresses alternation. This means the expressions will search for multiple patterns in the same string.

( )     Groups expressions to assist in alternation and back referencing.

[ ]     Looks for a set of characters.

(c) Pattern Quantifier:用来表示字符的数量关系。
*     Matchs 0 or more times.

+     Matchs 1 or more times.

?     Matchs 0 or 1 times.

{n}     Matches exactly n times.

{n,}     Matches at least n times.

{n,m}     Matches at least n times but no more than m times.

(d) Character Patterns:下列的sequence用来match一些特定格式的字符:
\r     Carriage return(CR), ASCII 13(十进制)

\n     New line, UNIX中代表ASCII 10(十进制), DOS(Windows)系统中则是ASCII 13 + ASCII 10(十进制).

\t     Tab, ASCII 9(十进制)

\w     Matches an alphanumeric character. Alphanumeric also includes _. 即 [A-Za-z0-9_].

\W     Matches a nonalphanumeric character. 即 [^A-Za-z0-9_].

\s     Matches a white space character. This includes space, tab, FormFeed and CR/LF. 即 [\ \t\f\r\n].

\S     Matches a non-whote space character. 即 [^\ \t\f\r\n].

\d     Matches a digit. 即 [0-9].

\D     Matches a nondigit character. 即 [^0-9].

\b     Matches a word boundary.

\B     Matches a nonword boundary.

\033     octal char

\x1B     hex char

(e) Examples:
Regular Expression这个东东非常强大、非常重要,但是对初学者来说简直是个恶梦,记得我当初刚接触时也是雾煞煞的,就算现在的我也不敢说全懂了,但你若了解了它的基本技巧后,包你爱不释手,每每为它强大的功能赞叹。上面那些表格相信你也是有看没有懂,这种东西要借由范例入门比较快,下面我列出一些基本范例,希望能帮助你了解它的基本技巧。

/abc/
找到含有abc的字符串

/^abc/
找到开头是abc的字符串

/abc$/
找到结尾是abc的字符串

/a|b/
找到有a或b的字符串,也可以用来找整个字(word)

/ab{2,4}c/
找到a后面跟着2-4个b,再跟着c的字符串,若只有/ab{2,}c/则会找二个以上的b

/ab*c/
找到a后面跟着0个或多个b,再跟着c的字符串,如同/ab{0,}c/

/ab+c/
找到a后面跟着一个以上的b,再跟着c的字符串,如同/ab{1,}c/

/a.c/
.可以代表任何字符,除了new line字符(\n)外。

/[abc]/
找到含有这三个字符中任何一个的字符串

/\d/
找到含有数字的字符串,如同/[0-9]/

/\w/
找到含有字母的字符串,如同/[a-zA-Z0-9_]/

/\s/
找到含有white space的字符串,如同/[ \t\r\n\f]/

/[^abc]/
找到没有abc任一字符的字符串

/\*/
找到含有字符*的字符串,在反斜线"\"后面的字符Perl会把它当作普通字符看待。若你不确定这个符号是否为特殊字符,干脆全加上\以策安全

/abc/i
忽略abc的大小写

/(\d+)\.(\d+)\.(\d+)\.(\d+)/
找到类似IP的字符串,并将IP的四个数字分别存在$1,$2,$3,$4四个特殊变数中,以便在其后加以利用。例:
if ($x =~ /(\d+\.\d+)\.\d+\.\d+/) {
print "海洋大学" if ($1 eq "140.121");
}

m//gimosx
m命令可以让你自订pattern的分隔符,而gimosx则是它的修饰选项,请参看(a)Modifiers。例如:

$url="my.machine.tw:8080/cgi-bin/test.pl";
($host, $port, $file)=($url=~m|http://([^/:]+):{0,1}(\d*)(\S*)$|);

这个Regular Expression相当复杂,主要目的是分析指定的URL,然后取得host名称、port号码及对应的档案。我一项项慢慢解释:

$url=~m||
m后面跟着的就是分隔符,| |里面的就是pattern。

([^/:]+)
match一个字符串,里面没有/和:字符。找到的字符串存在$1中。

:{0,1}(\d*)
match 0或1个:,后面跟着一串数字或nothing。找到的字符串存在$2中,若找不到,$2就是空的。

(\S*)$
match一串非空格符,并以找到的字符串为结尾。找到的字符串存在$3中。

()=()
($host, $port, $file)=($1, $2, $3)
即$host="my.machine.tw"
$port=8080
$file="/cgi-bin/test.pl"

s/PATTERN/REPLACEMENT/egimox
没错,这就是取代的命令。它会寻找符合PATTERN的字符串,并取代成REPLACEMENT字符串。它的修饰选项多了e选项,其它的和上面都一样,我将它列表如下:
e     Evaluate the right side as an expression.

g     Replace globally, i.e. all occurrences.

i     Do case-insensitive pattern matching.

m     Treat string as multiple lines.

o     Only compile pattern once.

s     Treat string as single line.

x     Use extended regular expressions.

例:
$x =~ s/\s+//g
把所有的white space全部去除掉

$x =~ s/([^ ]*):*([^ ]*)/$2:$1/
把用":"分开的两个字段互相对调

$path =~ s|/usr/bin|/usr/local/bin|
它也可以让你自订分隔符哦

tr/SEARCHLIST/REPLACEMENTLIST/cds
这是也是取代的命令,和上一个不同的是SEARCHLIST和REPLACEMENTLIST只能是普通字符串,而不是Regular Expression,所以速度比较快。它的修饰选项也比较少:
c     Complement the SEARCHLIST.

d     Delete found but unreplaced characters.

s     Squash duplicate replaced characters.

例:
$x =~ tr/this/that/
把"this"替换成"that"

$x =~ tr/a-z/A-Z/
把小写字母全部替换成大写字母

$count = $x =~ tr/*/*/
计算$x中有几个"*"

(6) Spectial Variables
Perl的特色之一就是有超过50个以上的特殊变量,这些变量都是全域变量,用来设定程序的执行环境和其它细节。若你想深入了解Perl程序设计,那么这些东西是不可或缺的。在这里我只列几个常用的特殊变量以供参考,有兴趣的人请自行查阅。
$_     The default input and pattern-searching space.

$digit     Contains the subpattern from a successful parentheses pattern match.

$.     The current input line number of last filehandle read.

$!     Contains the current value of errno.

$0     The name of the file of the Perl script.

@ARGV     The command line arguments issued when the script was started.

@_     The parameter array for subroutines.

%ENV     This associative array contains your current environment.

(7) Help
目前市面上有关Perl语言的书并不多,就算是原文书也只有那几本圣经本。不过只要是有关CGI的书,其内容大都会提到Perl,但却很少教到基本语法,常常使人一头雾水。所以我建议:如果你真的想学好Perl语言,真得想拿Perl来写程序,那我建议你最好去买一本书来看,在观念上会比较清楚,在实际应用上也会比较有帮助;如果你只是想写一些简单的CGI程序,或只想看得懂别人所写的CGI程序,那在网络上的数据就绰绰有余了。

其它资源就是Perl本身的man pages,你在unix账号下键入 man perl 就可以查阅了,这份文件做得不错,还根据Perl的各个部分写了man pages,如Perl syntax, builtin function, regular expression, data structure等,大家可以用man指令一一查询,有时候在写程序时一时忘了某个函数怎么用,这倒是个方便又快速的查询方法。

(8)函数
1. Perl函数
通过 & 调用.

2. Perl参数
Perl天然支持可变数目个参数。在函数内部,所有参数按顺序放在数组 @_ 中,在函数内部,$_[0] 表示函数的第一个参数,其余类推。

3. shift
shift 后跟一个数组,表示将数组的第一个值返回。数组也被改变,其第一个元素被弹出。

演示代码一(求最大值):
#!/usr/bin/perl -w
use strict;
# 调用函数max,取得一组数值的最大值,并输出。
my $maxCnt = &max(11,22,33);
print "maxCnt=$maxCnt\n";

sub max {
# 采用遍历算法。先将参数中的第一个值赋给$currentMaxCnt。
# @_ 是默认的包含本函数所有参数 [如(11,22,33)]的数组。
# shift @_ 有两个结果: 1. 将数组 @_ 中的第一个值做为返回值(赋给了$currentMaxCnt). 2. 将@_数组第一个值弹出[此后@_的值变为(22,33)].
my $currentMaxCnt = shift @_;
# 函数中使用shift时,@_可以省略。上面代码也可以写成这样。
#  my $currentMaxCnt = shift;

# 遍历整个@_数组。
foreach ( @_ ) {
# $_ 表示数组@_中当前被遍历到的元素.
if ( $_ > $currentMaxCnt ) {
# 如果发现当前数组元素比$currentMaxCnt大,那就将$currentMaxCnt重新赋值为当前元素。
$currentMaxCnt = $_;
}
}
# 函数返回值为标量$currentMaxCnt.
return $currentMaxCnt;
}

演示代码二(求和):
#!/usr/bin/perl -w
use strict;

# 求一组数的和并打印。
my $s1 = &sumvar(11,22,33);
my $s2 = &sumarg(22,33,44);
my $s3 = &sumgod(11,22,33,44,55);
print "s1=$s1, s2=$s2, s3=$s3\n";

# 办法1
sub sumvar {
# 将参数数组的前三个元素值相应地赋给($first, $second, $third)
(my $first, my $second, my $third) = @_;
# 返回其和值。缺点: 如果是求四个参数的和,依然只能给出前三个的和。
return $first + $second + $third;
}

# 办法2
sub sumarg {
# $_[0] 表示参数数组@_的第一个元素。其余类推。
my $first = $_[0];
my $second = $_[1];
my $third = $_[2];
# 返回其和值。缺点: 同sumvar. 只是通过这里学习 $_[0] 这种用法。
return $first + $second + $third;
}

# 办法3, 参数可以任意多。都能求其和。
sub sumgod{
my $s = shift @_;
foreach ( @_ ) {
$s = $s + $_;
}
# 同前面函数max。
return $s;
}

(8)总结
整理了一下自己觉得用的比较多的一些符号、用法、函数、库之类的,这些都是很基本的,但是“背熟”了,对提高效率会很有帮助。

数据操作
* $ - 声明与引用用一个scalar的变量
* @ - 声明与引用一个list,但是当访问一个list的成员时,需使用$ListName[index]
* % - 声明与引用一个hash表,但是当访问一个hash的成员时,需要使用$HashName{key}

特殊变量
* $0 - 当前运行脚本的文件名
* @ARGV - 当前运行脚本的命令行参数列表
* $_ - 默认变量,如循环中的当前变量
* @_ - 函数的输入参数列表
* %ENV - 系统的环境变量
* @INC - Perl的Include路径列表,我们可以往该列表中添加我们自己的目录来方便引用自定义的库
* $! - 当前系统提示,错误信息
* $^O - 操作系统的名字
* STDIN,STDOUT,STDERR - 输入输出的默认句柄,可以作一定的自定义
* => - 声明一个hash时可以用来明确的表示出key=>value的对应关系
* $^I- 指定备份的文件的后缀名,如此,被修改的文件将会自动以该后缀名保存一个副本

特殊用法
* &Sub - 调用一个函数,虽然Perl有些规则让你在某些时候可以省略这里的&符号,但是处于一致性考虑,所以自定义的函数的调用,我一律采用此种方式。
* $# - 用来取得模个数组的最大index, 一般情况下,也可以用-1来表示最后一个元素的index的
* qw() - 快速声明一个字符串数组,可以省略那些烦人的引号

正则表达式
* $ - 获取被括号捕获的匹配
* $`, $&, $' - 获取匹配的字符串,以及其前后两个部分
* ^,$ - 字符串的始末位置,用作定位

常用函数
* pop, push, shift, unshift, reverse - list的操作函数
* keys,values, exists, each, delete - hash的操作函数
* chomp, split, join, index, substr, sort - 字符串操作函数
* sprintf,printf, print - 格式化输出函数
* system, exec, `` - 系统命令调用函数
* glob, unlink, mkdir, rmdir, rename,chmod,chown, open, close, opendir, closedir - 文件系统操作函数
* stat, lstat,localtime,gmtime,utime - 文档属性,时间相关函数
* hex, oct - 二进制,八进制,十六进制数转化成十进制的函数
* grep, map - list高级操作函数

这些函数的详细介绍,都可以通过命令:
#perldoc -f functionname
查到

常用库
* File::Basename - 根据path获取文件名或者文件路径
* File::Spec - 根据文件名与路径组合成全路经
* File::Find - 递归遍历某个目录下所有文件
* XML::Simple - 以一个复杂的结构来表示xml文件,使用起来相当方便
* Time::HiRes - 经常用来计算一个操作所耗费的时间
* Getopt::Long - 当脚本需要复杂的输入参数与选项时用到
* Cwd - 拿到当前工作目录
* IO::File - 文件操作
* Win32 - 当需要调用一些Windows API时我会用它

当然,这些库的详细介绍都可以在CPAN看到。

该文章最后由 阿炯 于 2021-08-01 19:06:57 更新,目前是第 6 版。