perl简单语句的修饰符

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\n";
print if /abc/;      #====>输出xabcy
#case3
$_="I lost my gloves in the clover.";
print "Found love in gloves!\n" if /love/;        
                     #====>输出Found love in gloves!
#case4
my $i = 0;
while(1)
{
    last if $i > 5; #当i>=5时,while循环结束
    print "\$i:$i\n";
    $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++,"\n" 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,"\n");
print foreach @alpha;      #====>abcdefghijkmnopqrstuvwxyz

总结

使用修饰符的写法会使程序更加紧凑, 从一定程度减少了大括号的写法,这种简洁写法适用于大括号内的只有一句时才可以这么写。等价写法如下:

$x=5;

#简洁写法
print $x if $x == 5; 

#等价写法
if ($x == 5)
{
    print $x;
}

from:https://www.cnblogs.com/wanming88/p/4143556.html

转载于:https://www.cnblogs.com/jinxiang1224/p/8468197.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值