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
    ";
    }
    

      

  • 相关阅读:
    面试题3,求101-200之间有多少个素数,并且输出所有素数
    面试题2,兔子问题
    plsql 导入导出表数据与表结构
    plsql 的各个窗口区别
    oracle cmd命令
    ora-01017 用户名密码未登录
    PLSQL登录报错ORA-12154
    看oracle 的数据库位数
    plsql Developer 登录oracle出现 initialization error
    plsql dev 12 版下载地址
  • 原文地址:https://www.cnblogs.com/pxy7896/p/6768934.html
Copyright © 2011-2022 走看看