標籤:
下面是日常工作中一些程式碼片段的總結,部分注釋是後加的,採用了//這種形式,請勿套用。
1.取得使用者輸入
print("Please input the date range:");
$dateRange=<STDIN>;
chomp($dateRange);
2.如果資料不符合要求退出程式
if(!isValidDateRange($dateRange)){
die("Wrong date range\n");
}
3.劈分字串得到數組
my @arrDate=split(/\s*[~,-]\s*/,$dateRange);
[email protected][0];
[email protected][-1]; // 倒數第一個,perl數組的這個特性真是太貼心了,比C一脈的長度減一要省事不少,不過也有elsif這種你奈我何的任性設計
4.在螢幕上列印文本
print("Reading file...\n");
5.逐行讀取檔案
my @arrFileFound;
open(FOF, $fof) || die "Could not read $fof:$!";
while ($line = <FOF>){
# read a line from file
chomp($line);
# fill the arrFileFound with line
push(@arrFileFound,$line); // 讀出的行放入數組
}
close(FOF);
6.數組排序
@arrFileFound=sort(@arrFileFound);
7.遍曆數組
# 初始化數組
@annoNames=("danile","iria","jinwn","ka","manzhez","marna","max_nglish","mohmed","roxna","thir","trno","trno_english","transtc_en");
[email protected];// 取數組長度
$iNames=0; // 遍曆下標
while($iNames<$nNames){
$annoName=$annoNames[$iNames];
# do sth
...
$iNames++;
}
8.將數組作為參數傳入函數
函數定義:
sub printAnnologs{
local($annotator,*files)[email protected]_;
[email protected];
$i=0;
while($i<$n){
my [email protected][$i];
...
$i++;
}
}
調用方式
&printAnnologs($annoName,*annologs);
9.判斷某字串是否包含另一字串
sub isValidAnnotator{
local($name)[email protected]_;
my $names="danile","iria","jinwn","ka","manzhez","marna","max_nglish","mohmed","roxna","thir","trno","trno_entac_en";
return index($names,$name)!=-1;
}
10.Regex模式比對
sub isValidDateRange{
local($date)[email protected]_;
return $date=~/^\d{8}\s*[-~,]\s*\d{8}$/;
}
相關文章:http://www.cnblogs.com/xiandedanteng/p/3250688.html
Some perl tips