为 Java 程序员准备的 10 分钟 Perl 教程

3. 条件、循环表达式

Perl为条件和循环语句准备了if, while, for, foreach等关键字,这与Java非常类似(switch除外)。

详情请见下面的代码:

01#if my $condition = 0; 02if($condition== 0){ 03print"=0\n"; 04} 05elsif($condition== 1){ 06print"=1\n"; 07} 08else{ 09print"others\n"; 10} 11 12 13#while while($condition < 5){ 14print$condition; 15$condition++; 16} 17for(my$i=0;$i< 5;$i++){ 18print$i; 19} 20 21#foreach my @anArray = ("a", 1, 'c'); 22foreachmy$aScalar(sort@anArray){ 23print$aScalar."\n"; 24}

4.文件的读写

下面这个例子向我们展示了如何读写文件。这里请注意">"和">>"之间的区别,">>"在文件末尾追加内容,">"创建一个新的文件储存信息。

01#read from a file 02my$file="input.txt"; 03open(my$fh,"<",$file) ordie"cannot open < $file!"; 04while(my$aline= <$fh> ) { 05#chomp so no new line character 06chomp($aline); 07print$aline; 08} 09 10close$fh; 11 12# write to a file 13my$output="output.txt"; 14open(my$fhOutput,">",$output) ordie("Error: Cannot open $output file!"); 15print$fhOutput"something"; 16close$fhOutput;

5.正则表达式

Perl中有两种使用正则表达式的方法:m和s。

下面的代码在$str上应用了正则表达式。

1$str=~ m/program<span>(</span>creek|river)/

如果$str的内容是“programcreek”,表达式将会返回true。这也可以被用于条件判断或循环。每一件事都要用多方面的角度来看它

为 Java 程序员准备的 10 分钟 Perl 教程

相关文章:

你感兴趣的文章:

标签云: