下面是日常工作中一些代码片段的总结,部分注释是后加的,采用了//这种形式,请勿套用。
1.取得用户输入
print("Please input the date range:");
$dateRange=<STDIN>;
chomp($dateRange);
2.如果数据不符合要求退出程序
if(!isValidDateRange($dateRange)){
die("Wrong date range
");
}
3.劈分字符串得到数组
my @arrDate=split(/s*[~,-]s*/,$dateRange);
$startDate=@arrDate[0];
$endDate=@arrDate[-1]; // 倒数第一个,perl数组的这个特性真是太贴心了,比C一脉的长度减一要省事不少,不过也有elsif这种你奈我何的任性设计
4.在屏幕上打印文本
print("Reading file...
");
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");
$nNames=@annoNames;// 取数组长度
$iNames=0; // 遍历下标
while($iNames<$nNames){
$annoName=$annoNames[$iNames];
# do sth
...
$iNames++;
}
8.将数组作为参数传入函数
函数定义:
sub printAnnologs{
local($annotator,*files)=@_;
$n=@files;
$i=0;
while($i<$n){
my $file=@files[$i];
...
$i++;
}
}
调用方式
&printAnnologs($annoName,*annologs);
9.判断某字符串是否包含另一字符串
sub isValidAnnotator{
local($name)=@_;
my $names="danile","iria","jinwn","ka","manzhez","marna","max_nglish","mohmed","roxna","thir","trno","trno_entac_en";
return index($names,$name)!=-1;
}
10.正则表达式模式匹配
sub isValidDateRange{
local($date)=@_;
return $date=~/^d{8}s*[-~,]s*d{8}$/;
}
11.字符串替换
#将$newfile中的USA替换成America
my $newfile="ChinaBeijingUSANewyork";
$newfile=~s/USA/America/;