3. 条件、循环表达式
Perl为条件和循环语句准备了if, while, for, foreach等关键字,这与Java非常类似(switch除外)。
详情请见下面的代码:
01
02
if
(
$condition
== 0){
03
print
"=0\n"
;
04
}
05
elsif
(
$condition
== 1){
06
print
"=1\n"
;
07
}
08
else
{
09
print
"others\n"
;
10
}
11
12
13
14
print
$condition
;
15
$condition
++;
16
}
17
for
(
my
$i
=0;
$i
< 5;
$i
++){
18
print
$i
;
19
}
20
21
22
foreach
my
$aScalar
(
sort
@anArray
){
23
print
$aScalar
.
"\n"
;
24
}
4.文件的读写
下面这个例子向我们展示了如何读写文件。这里请注意">"和">>"之间的区别,">>"在文件末尾追加内容,">"创建一个新的文件储存信息。
01
02
my
$file
=
"input.txt"
;
03
open
(
my
$fh
,
"<"
,
$file
) or
die
"cannot open < $file!"
;
04
while
(
my
$aline
= <
$fh
> ) {
05
06
chomp
(
$aline
);
07
print
$aline
;
08
}
09
10
close
$fh
;
11
12
13
my
$output
=
"output.txt"
;
14
open
(
my
$fhOutput
,
">"
,
$output
) or
die
(
"Error: Cannot open $output file!"
);
15
print
$fhOutput
"something"
;
16
close
$fhOutput
;
5.正则表达式
Perl中有两种使用正则表达式的方法:m和s。
下面的代码在$str上应用了正则表达式。
1
$str
=~ m/program<span>(</span>creek|river)/
如果$str的内容是“programcreek”,表达式将会返回true。这也可以被用于条件判断或循环。