1.從基礎(chǔ)開(kāi)始
不像java,Perl不需要“main”方法作為入口點(diǎn)。要運(yùn)行一個(gè)簡(jiǎn)單的Perl程序如下:
代碼如下:
# comment starts with "#"
# the name is hello.pl
print "Hello Perl!";
只需執(zhí)行:
perl hello.pl
2. 日期類型
在Perl中的日期類型是非常簡(jiǎn)單,它有3種類型:標(biāo)量,數(shù)組和Hash。
標(biāo)是一個(gè)單值,它基本上可以是任何其他比數(shù)組或哈希。
數(shù)組是一個(gè)數(shù)組,可以包含不同類型的元素,如整數(shù),字符串。
哈希基本上是像Java的HashMap中。
將下面的代碼結(jié)合所有的使用情況。
代碼如下:
#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";
}
輸出結(jié)果:
代碼如下:
e
c
a
d
如果你想對(duì)數(shù)組進(jìn)行排序,你可以簡(jiǎn)單地使用類似下面的排序功能:
代碼如下:
foreach my $aScalar (sort @anArray){
print $aScalar."/n";
}
3. 條件、循環(huán)表達(dá)式
Perl為條件和循環(huán)語(yǔ)句準(zhǔn)備了if, while, for, foreach等關(guān)鍵字,這與Java非常類似(switch除外)。
詳情請(qǐng)見(jiàn)下面的代碼:
代碼如下:
#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.文件的讀寫
下面這個(gè)例子向我們展示了如何讀寫文件。這里請(qǐng)注意">"和">>"之間的區(qū)別,">>"在文件末尾追加內(nèi)容,">"創(chuàng)建一個(gè)新的文件儲(chǔ)存信息。
代碼如下:
#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.正則表達(dá)式
Perl中有兩種使用正則表達(dá)式的方法:m和s。
下面的代碼在$str上應(yīng)用了正則表達(dá)式。
代碼如下:$str =~ m/program<SPAN>(</SPAN>creek|river)/
新聞熱點(diǎn)
疑難解答
圖片精選