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

或者极简形式:

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

  

posted @ 2017-04-26 15:41  陆离可  阅读(215)  评论(0编辑  收藏  举报