• perl-basic-分支&循环


    • if
    1. elsif
    2. shorter if: if+condition放在句子尾部。
    use strict;
    use warnings;
    
    my $word = "antidisestablishmentarianism";
    # get the length of a scalar
    my $strlen = length $word;
    
    if($strlen >= 15) {
    	print "'", $word, "' is a very long word";
    # elsif
    } elsif(10 <= $strlen && $strlen < 15) {
    	print "'", $word, "' is a medium-length word";
    } else {
    	print "'", $word, "' is a short word";
    }
    # short form of IF
    print "'", $word, "' is actually enormous" if $strlen >= 20;
    
    • unless...if
    my $temperature = 10;
    
    unless($temperature > 30) {
    # condition is false
    	print $temperature, " degrees Celsius is not very hot";
    } else {
    # condition is true
    	print $temperature, " degrees Celsius is actually pretty hot";
    }
    # condition is false, then print
    print "Oh no it's too cold" unless $temperature > 15;
    
    • 允许使用三元运算符?:且可以嵌套:
    my $eggs = 5;
    print "You have ", $eggs == 0 ? "no eggs" :
                       $eggs == 1 ? "an egg"  :
                       "some eggs";
    

     


    • while(),until(), do...while,do...until和for类似c
    • 循环一个数组时不必用for循环。。用foreach
    my @arr = ("hi", "my", "lady");
    foreach my $str (@arr) {
        print $str;
        print "
    ";
        }  

    或者极简形式:

    print $_ foreach @arr;

    如果需要索引值,用这个:

    foreach my $i ( 0 .. $#arr ) {
    	print $i, ": ", $arr[$i];
    }
    
    • 循环hash时:因为用keys返回hash的key是无序的,所以先用sort排序。
    foreach my $key (sort keys %scientists) {
    	print $key, ": ", $scientists{$key};
    }
    
    • 循环控制:next = continue, last = break, 可以从循环中跳转到label处,label必须全大写
    CANDIDATE: for my $candidate ( 2 .. 100 ) {
    	for my $divisor ( 2 .. sqrt $candidate ) {
    		next CANDIDATE if $candidate % $divisor == 0;
    	}
    	print $candidate." is prime
    ";
    }
    

      

  • 相关阅读:
    hdu 3652 【数位dp】
    02 -body标签中相关标签
    01-html介绍和head标签
    python 核心编程第九章文件
    python核心编程 第七章 字典,集合 练习
    常用链接
    python核心编程 第七章 字典
    python核心编程 第六章 字符串,元组,列表 字符串元组只读不可变。列表可变。
    python核心编程 第五章 数字
    python读取文件中的路径内容,保存到另外的路径中
  • 原文地址:https://www.cnblogs.com/pxy7896/p/6768934.html
Copyright © 2020-2023  润新知