国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Perl > 正文

為Java程序員準備的10分鐘Perl教程

2020-06-04 20:31:53
字體:
來源:轉載
供稿:網友

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)/

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 贵港市| 宜君县| 嵊泗县| 翁牛特旗| 炎陵县| 江阴市| 太仆寺旗| 滨海县| 兴化市| 汽车| 时尚| 涟源市| 乡城县| 留坝县| 修水县| 股票| 新密市| 中宁县| 固阳县| 郯城县| 博爱县| 罗江县| 随州市| 巧家县| 绥宁县| 武川县| 仁化县| 河东区| 南丰县| 安平县| 长沙市| 雷山县| 杭锦后旗| 阿巴嘎旗| 五大连池市| 安化县| 滦平县| 沙河市| 英山县| 长汀县| 昌黎县|