Some perl tips

來源:互聯網
上載者:User

標籤:

下面是日常工作中一些程式碼片段的總結,部分注釋是後加的,採用了//這種形式,請勿套用。

 

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.