perl中常见的简单语句修饰符有 if unless while until foreach,它们demo语句分别如下:
1. if 条件修饰符
格式:
Expression2 if Expression1 如果Expression1表达式为真,则执行Expression2表达式内容。
#case1
$x=5;
print $x if $x==5; #====>输出5
#case2
$_="xabcy
";
print if /abc/; #====>输出xabcy
#case3
$_="I lost my gloves in the clover.";
print "Found love in gloves!
" if /love/;
#====>输出Found love in gloves!
#case4
my $i = 0;
while(1)
{
last if $i > 5; #当i>=5时,while循环结束
print "$i:$i
";
$i++;
}
2. unless条件修饰符
格式:
Expression2 unless Expression1 如果Expression1为假,则执行Expression2表达式内容。
#demo
$x=5;
print $x unless $x==6; #====>输出5
3. while循环修饰符
格式:
Expression2 while Expression1 只要第一个表达式为真,while循环修饰符便会重复执行第二个表达式。
#demo
$x=1;
print $x++,"
" while $x!=5; #====>输出1,2,3,4
4. until
格式:
Expression2 until Expression1 只要第一个表达式为假, until循环修饰符便会重复执行第二个表达式
#demo
$x=1;
print $x++,"/n" until $x==5; #====>输出1,2,3,4
5. foreach
会逐个判断列表中每个元素的值,并通过标量$_以此引用各个列表元素。
@alpha=(a .. z,"
");
print foreach @alpha; #====>abcdefghijkmnopqrstuvwxyz
总结
使用修饰符的写法会使程序更加紧凑, 从一定程度减少了大括号的写法,这种简洁写法适用于大括号内的只有一句时才可以这么写。等价写法如下:
$x=5;
#简洁写法
print $x if $x == 5;
#等价写法
if ($x == 5)
{
print $x;
}