perl控制結構學習筆記
一.條件判斷
if ( )
{
}
elsif ( )
{
}
...
else
{
}
實例
#!/usr/bin/perl
use strict;
use warnings;
my $in =<STDIN>; #用戶輸入一個數字
chomp($in);
if($in>90){ #如果輸入數字大於90 則大於 $IN>a
print '$in>a';
}else{ #否則打印$IN <a
print '$in<a';
}
二.循環
1.while循環
while ( )
{
}
2.until循環 #條件為假是執行循環
until ( )
{
}
實例
#!/usr/bin/perl
use strict;
use warnings;
my $i = 1; my $j = 10;
until($i>$j){ #$i>$j 此處條件為假
$i++;
print "Hello\n";
}
打印結果
---------- Perl ----------
2
3
4
5
6
7
8
9
10
11
Output completed (0 sec consumed) - Normal Termination
結論從打印結果可以看出 只要until循環滿足 判斷條件為假 執行條件真時結束循環。實例可以看出 當$i =11 時 $i>$j 條件為真 結束循環。
3.類C的for循環
for ($count=1; $count <= 5; $count++)
{
#statements inside the loop go here
4.針對列表(數組)每個元素的foreach循環
foreach localvar (listexpr)
{
statement_block;
}
註:
(1)此處的循環變量localvar是個局部變量,如果在此之前它已有值,則循環後仍恢復該值.
(2)在循環中改變局部變量,相應的數組變量也會改變.
例:
foreach $word (@words)
{
if ($word eq "the")
{
print ("found the word 'the'\n");
}
}
此外,如果localvar省略了的話,PERL將使用默認變量$_.
例:
@array = (123, 456, 789);
foreach (@array)
{
print $_;
}
$_是PERL最常使用的默認變量,上例中print後面的$_也可以去掉,當print沒有參數時,會默認輸出$_變量.
5.do循環
do
{
statement_block
} while_or_until(condexpr);
do循環至少執行一次循環.
6.循環控制
退出循環為last,與C中的break作用相同;
執行下一個循環為next,與C中的continue作用相同;
PERL特有的一個命令是redo,其含義是重復此次循環,即循環變量不變,回到循環起始點.但要註意,redo命令在do循環中不起作用.
三.單行條件
語法為statement keyword condexpr.其中keyword可為if, unless, while或until.例如:
print ("This is zero.\n") if ($var == 0);
print ("This is zero.\n") unless ($var != 0);
print ("Not zero yet.\n") while ($var-- > 0);
print ("Not zero yet.\n") until ($var-- == 0);
雖然條件判斷寫在後面,但卻是先執行的。
perl控制結構學習筆記