zoukankan      html  css  js  c++  java
  • 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
    ";
    }
    

      

  • 相关阅读:
    tornado中form表单验证详解
    关于tornado中session的总结
    Linux常用命令
    css3动画属性详解 与超酷例子
    keepalive高可用的健康检查
    keepalive的nginx防火墙问题
    安装配置hadoop
    tmux的简单快捷键
    部署使用elk
    k8s搭建部署
  • 原文地址:https://www.cnblogs.com/pxy7896/p/6768934.html
Copyright © 2011-2022 走看看