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