本文共 3005 字,大约阅读时间需要 10 分钟。
目录
数字标量,0为假,其他数字为真;
字符串标量,''为假,其他为真;
其它先转化为以上两种再判断;
"!"表示取反。
运算符 含义 实例
and(&&) 且 condition1 and condition2,两个条件都为真,返回真
or(||) 或 condition1 or condition2,两个条件有一个为真,返回真
not(!) 取反 not condition1,条件为真,取反则为假
if (condition){#条件为真时执行
do something.....
}else{
do something else......
}
例如,ifelse.pl
#!/usr/bin/perluse strict;use warnings;my $str1 = $ARGV[0];my $str2 = $ARGV[1];if($str1 == $str2){        print "EQ numbers, good job!\n";}elsif($str1>$str2){        print "Bigger numbers, go on!\n";}else{        print "Over!\n";}   perl ifelse.pl 1 1
EQ numbers, good job!
perl ifelse.pl 2 1
Bigger numbers, go on!
perl ifelse.pl 2 3
Over!
unless(condition)){#条件为假时执行
do somesthing...
}else{
do something else
}
例如,unless1.pl
#!/usr/bin/perluse strict;use warnings;my $str1=$ARGV[0];my $str2=$ARGV[1];unless($str1!=$str2){        print "EQ numbers!\n";}else{        print "NE numbers!\n";}   perl unless1.pl 1 1
EQ numbers!
perl unless1.pl 1 2
NE numbers!
expression ? true_value : false_value
如果expression为真,整个表达式返回true_value;如果expression为假,整个表达式返回false_value;
例如,ternary_operator.pl
#!/usr/bin/perluse strict;use warnings;my $result=($ARGV[0]==$ARGV[1] ? "EQ numbers" : "NE numbers");print "$result\n";
perl ternary_operator.pl 1 2
NE numbers
perl ternary_operator.pl 1 1
EQ numbers
while(condition){
do something..
}
例如,while1.pl
#!/usr/bin/perluse strict;use warnings;my $in=5;while($in<10){        print "$in\n";        $in+=2;}   perl while1.pl
5
7
9
for(start;expression1;expression2){
do something.....
}
例如,for1.pl
#!/usr/bin/perluse strict;use warnings;for(my $i=5;$i<10;$i+=2){        print "$i\n";}   perl for1.pl
5
7
9
#以下两种方式结果相同,例如,foreach1.pl
#!/usr/bin/perluse strict;use warnings;foreach (5..10){        print "$_\n";}print "\n";foreach my $i (5..10){        print "$i\n";}   perl foreach1.pl
5
6
7
8
9
10
5
6
7
8
9
10
例如,while_each1.pl
#!/usr/bin/perluse strict;use warnings;my %hash=(        "apple"=>"fruit",        "tomat"=>"vegetables",        "tomat1"=>"vegetables");#定义哈希,使用()而不是{}while(my($k,$v)=each %hash){        print "$k\t$v\n";}   perl while_each1.pl
tomat vegetables
apple fruit
tomat1 vegetables
退出当前层次的循环,不会退出外层循环,类似python中的break。
例如,last1.pl
#!/usr/bin/perluse strict;use warnings;my $in=2;foreach (1..20){        last if $_%$in == 0;#当遇到能被2整除的数时,跳出当前循环        print "$_\n";}   perl last1.pl
1
跳过本次循环,进入下一轮循环,类似python中的continue。
例如,next1.pl
#!/usr/bin/perluse strict;use warnings;my $in=2;foreach (1..20){        next if $_%$in == 0;#跳过能被2整除的数        print "$_\n";}   perl next1.pl
1
3
5
7
9
11
13
15
17
19
忽略之后的语句,重新执行本次循环。
例如,redo1.pl
#!/usr/bin/perluse strict;use warnings;my @array;for my $i (1..3){        push @array, $i;        redo if(@array == 2);#重新执行push @array, $i;}print "@array\n";   perl redo1.pl
1 2 2 3
print "True.\n" if $a > $b;#if $a > $b为真,执行print语句;

同名公众号,持续分享数据科学和生物信息优质内容。
转载地址:http://cbmwz.baihongyu.com/