perl学习2: 控制程序流 (foreach是核心)
文章目录
前言
提示:这里可以添加本文要记录的大概内容:
-  语句块
-  运算符
-  循环
-  标号
-  退出perl
1.语句块:if语句(几乎与C语言类似,除了elsif)
$r = 10;
if ($r == 10){
    print '$r is 10!';
}
elsif ($r == 20){
    print '$r is 20!';
}
else{
    print '$r is neither 10 nor 20.'
}
# 如果只有一个条件可以把if放到后面
print "Hello!" if (1 == 1);
2.字符关系运算符(类似于=, >, <, >=, <=, !=)?
- eq等于;
- gt大于;
- lt小于;
- ge大于等于;
- le小于等于;
- ne不等于;
perl中有哪些假值? 0;“”;‘’;‘0’;“0”;undef;
 逻辑运算符有哪些? and; or; not;
代码如下(示例):
if ($x and $y and not $z){
    print "All conditions met.\n";
}else{
    print "Not all.\n"
}
逻辑运算符短路,即一旦确定表达式是真或假,就立即停止逻辑表达式的计算,最常见的是
open(FILE, "test.txt") or die "can't open file:$!\n";
3.循环语句(与C语言完全相同)
$count = 0;
while ($count <= 10){
    print "$count\n";
    $count++;
}
for($i; $i <= 10; $i++){
    print "i is now $i\n";
}
#高级perl技巧:使用foreach进行遍历
@name = qw(li zhi xin);
print "my name is ";
foreach $name (@name){  # $name是对@name中元素的引用,可以修改@name
    print "$name "
}
4.流程控制工具
last语句(退出当前循环)(等同于C里的break)
$count = 1;
while($count <= 15){
    last if ($count == 5);
    print "$count\n";
    $count++;
}
for($i=0; $i <= 100; $i++){
    for($j=0; $j <= 100; $j++){
        if ($i * $j == 140){
            print "The product of $i and $j is 140.\n";
            last;
        }
    }
}
next语句(回到当前循环头部)(等同于C里的continue)
for($i=0; $i <= 100; $i++){
    next if (not $i % 2);
    print "An odd number = $i\n";
}
语句块和循环语句可以设置标号,last、redo 和 next都可以带一个标号。(等价于C的loop语句)
 退出perl? exit 0;代表正常退出perl。










