4.1 简单语句
一个简单语句是一个表达式,因为副作用而计算。每条简单语句都必须以分号结尾,除非它是一个块中的最后一句。
4.2 if else 语句:
[oracle@jhoa 20150319]$ cat 1.pl
if (( my $color = <STDIN>) =~ /red/i ) {
$value = 1;
}
elsif ($color =~ /green/i) {
$value = 2;
}
elsif ($color =~ /blue/i) {
$value = 3;
}
else {
print "unknown"; $value=4;
}
print "$value is $value
";
4.3.3 foreach 循环:
累加 $value
[oracle@jhoa 20150319]$ cat 2.pl
@array = qw/1 2 3 4 5 6 7 8 9 10/;
$sum = 0; foreach $value (@array) { $sum += $value }
print "$sum is $sum
";
[oracle@jhoa 20150319]$ perl 2.pl
$sum is 55
[oracle@jhoa 20150319]$ cat 2.pl
@array = qw/1 2 3 4 5 6 7 8 9 10/;
$sum = 0; foreach $value (@array) { $sum = $value + $sum }
print "$sum is $sum
";
[oracle@jhoa 20150319]$
[oracle@jhoa 20150319]$ perl 2.pl
$sum is 55
last 退出循环:
[oracle@jhoa 20150319]$ cat 4.pl
for ($i = 2;$i<10;$i=$i+2){
for ($j=3;$j <5;$j++){
if ($i > $j){
last; ###退出内层循环
}
print "1--$i is $i
";
print "1--$j is $j
";
}
print "2---$i is $i
";
print "2---$j is $j
";
}
[oracle@jhoa 20150319]$ perl 4.pl
1--$i is 2
1--$j is 3
1--$i is 2
1--$j is 4
2---$i is 2
2---$j is 5
2---$i is 4
2---$j is 3
2---$i is 6
2---$j is 3
2---$i is 8
2---$j is 3
for ($j=3;$j <5;$j++){ 这层循环退出
4.4 光块
return 只能用于子程序(或者eval)块
[oracle@jhoa 20150319]$ cat 5.pl
$var="111111";
return 1;
[oracle@jhoa 20150319]$ perl 5.pl
Can't return outside a subroutine at 5.pl line 2.
$dbh = DBI->connect("dbi:Oracle:$DATABASE", "$USERID", "$PASSWORD", {PrintError => 0});
$dbh->do("TRUNCATE TABLE $DESTSCHEMA.F_EVT_CADC_SRLFREEZE") or die($DBI::errstr);
闭包:
[oracle@jhoa 20150319]$ cat a1.pl
use strict;
$var='aaaaaa';
[oracle@jhoa 20150319]$ perl a1.pl
Global symbol "$var" requires explicit package name at a1.pl line 2.
Execution of a1.pl aborted due to compilation errors.
use strict会限制全局变量的使用
use strict;
our $var='aaaaaa';
明确声明全局变量
为了又更好的颗粒度和提高效率,你可以用圆括号捕捉你特别想分离出来的部分。每对圆括弧捕捉与圆括弧内的
模式相匹配的子模式。圆括弧由左圆括弧的位置从左到右一次排序,对应的那些子模式的子字串在匹配之后可以
通过顺序的变量$1,$2,$3等等获得:
[oracle@jhoa 20150319]$ cat a2.pl
$_ = "Bilbo Baggins's birthday is September 22";
/(.*)'s birthday is (.*)/;
print "Person:$1
";
print "Person:$2
";
[oracle@jhoa 20150319]$ perl a2.pl
Person:Bilbo Baggins
Person:September 22