Some perl tips

本文总结了日常工作中涉及的代码片段,包括用户输入处理、日期范围验证、文件读取与排序、数组操作、字符串替换等核心编程技巧,并介绍了相关的正则表达式模式匹配与函数调用方法。

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

 

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}$/;
}

 

11.字符串替换
#将$newfile中的USA替换成America
my $newfile="ChinaBeijingUSANewyork";
$newfile=~s/USA/America/;

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值