控制结构
Perl支持很多种与C类似的控制结构,但是也与Pascal很相似。下面我们分别对着这些结构进行讨论。
foreach
Perl使用foreach结构对数组或其它列表结构中的每行进行操作:
foreach $morsel (@food) # Visit each item in turn
# and call it $morsel
{
print "$morsel\n"; # Print the item
print "Yum yum\n"; # That was nice
}
每次的操作过程被包围在花括号内。程序块中的$morsel第一次被赋予@food数组中的第一个值,然后被赋予数组的第二个值,依次类推。如果@food是空的,那么程序块将不会被执行。
判断
判断是检验表达式结果是真是假的一种结构。在Perl中,任何非0数字和非空字符串被看作真。数字0、0字符串和空字符串被看作假。下面是一些基于数字和字符串的判断:
$a == $b # Is $a numerically equal to $b? # Beware: Don't use the = operator. $a != $b # Is $a numerically unequal to $b? $a eq $b # Is $a string-equal to $b? $a ne $b # Is $a string-unequal to $b?
也可以用逻辑与、或、非:
($a && $b) # Is $a and $b true? ($a || $b) # Is either $a or $b true? !($a) # is $a false?
for
Perl的for结构与C的类似:
for (initialise; test; inc)
{
first_action;
second_action;
etc
}
语句initialise被首先执行,然后当test为真时程序块被执行。程序块每执行一次,inc发生一次。下面是一个循环打印数字0到9的循环:
for ($i = 0; $i < 10; ++$i) # Start with $i = 1
# Do it while $i < 10
# Increment $i before repeating
{
print "$i\n";
}
while和until
下面是一个从键盘读输入,知道口令正确为止的程序:
#!/usr/local/bin/perl
print "Password? "; # Ask for input
$a = <STDIN>; # Get input
chop $a; # Remove the newline at end
while ($a ne "fred") # While input is wrong...
{
print "sorry. Again? "; # Ask again
$a = <STDIN>; # Get input again
chop $a; # Chop off newline again
}
当键盘输入与口令不同时花括号内的程序块被执行。while结构很清晰,但有几点要注意:第一,我们可以从标准输入读入信息,而不用打开文件。第二,当口令被输入时,$a被赋予包括换行符在结尾的值。chop函数删除字符串的最后一个字符,这里是换行符。
until也可以执行相同的工作。程序块被反复执行,直到表达式为真。
另一种方式是把while或until放在程序块的后面。这要求do放在程序块的开始处,而判断在结尾处。这样程序可以这样写:
#!/usr/local/bin/perl
do
{
"Password? "; # Ask for input
$a = <STDIN>; # Get input
chop $a; # Chop off newline
}
while ($a ne "fred") # Redo while wrong input