码迷,mamicode.com
首页 > 其他好文 > 详细

Some perl tips

时间:2015-01-25 10:57:49      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

下面是日常工作中一些代码片段的总结,部分注释是后加的,采用了//这种形式,请勿套用。

 

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);
$startDate=@arrDate[0];
$endDate=@arrDate[-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");
$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}$/;
}

相关文章:http://www.cnblogs.com/xiandedanteng/p/3250688.html

Some perl tips

标签:

原文地址:http://www.cnblogs.com/xiandedanteng/p/4247853.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!