1.从基础开始
不像java,Perl不需要“main”方法作为入口点。要运行一个简单的Perl程序如下:
 代码如下:
# comment starts with "#" 
# the name is hello.pl 
print "Hello Perl!";
只需执行:
perl hello.pl
2. 日期类型
在Perl中的日期类型是非常简单,它有3种类型:标量,数组和Hash。
标是一个单值,它基本上可以是任何其他比数组或哈希。 
数组是一个数组,可以包含不同类型的元素,如整数,字符串。 
哈希基本上是像Java的HashMap中。
将下面的代码结合所有的使用情况。
 代码如下:
#claim a hash and assign some values
my %aHash;
$aHash{'a'}=0;
$aHash{'b'}=1;
$aHash{'c'}=2;
$aHash{'d'}=3;
$aHash{'e'}=4;
#put all keys to an array
my @anArray = keys (%aHash);
#loop array and output each scalar
foreach my $aScalar (@anArray){
 print $aScalar."/n";
}
输出结果:
 代码如下:
e
c
a
d 
如果你想对数组进行排序,你可以简单地使用类似下面的排序功能:
 代码如下:
foreach my $aScalar (sort @anArray){
 print $aScalar."/n";
}
3. 条件、循环表达式
Perl为条件和循环语句准备了if, while, for, foreach等关键字,这与Java非常类似(switch除外)。
详情请见下面的代码:
 代码如下:
#if my $condition = 0; 
if( $condition == 0){ 
    print "=0/n"; 
}
elsif($condition == 1){ 
    print "=1/n"; 
}
else{ 
    print "others/n";
}
 
#while while($condition < 5){ 
    print $condition;
    $condition++;
} 
for(my $i=0; $i< 5; $i++){ 
    print $i;
}
#foreach my @anArray = ("a", 1, 'c'); 
    foreach my $aScalar (sort @anArray){ 
        print $aScalar."/n";
}
4.文件的读写
下面这个例子向我们展示了如何读写文件。这里请注意">"和">>"之间的区别,">>"在文件末尾追加内容,">"创建一个新的文件储存信息。
 代码如下:
#read from a file 
my $file = "input.txt"; 
open(my $fh, "<", $file) or die "cannot open < $file!"; 
while ( my $aline = <$fh> ) {
    #chomp so no new line character 
    chomp($aline); 
    print $aline;
} 
close $fh;
# write to a file 
my $output = "output.txt"; 
open (my $fhOutput, ">", $output) or die("Error: Cannot open $output file!"); 
print $fhOutput "something"; 
close $fhOutput;
5.正则表达式
Perl中有两种使用正则表达式的方法:m和s。
下面的代码在$str上应用了正则表达式。
代码如下:$str =~ m/program<SPAN>(</SPAN>creek|river)/
新闻热点
疑难解答