perl學習【轉載+積累】

基本信息
    Perl通常被稱爲「實用報表提取語言」(Practical Extraction and Report Language)。Perl 最初的設計者爲拉里·沃爾(Larry Wall),他於1987年12月18日發表。Perl借取了C、sed、awk、shell scripting以及不少其餘程序語言的特性。其中最重要的特性是它內部集成了正則表達式的功能,以及巨大的第三方代碼庫CPAN,即Perl綜合典藏網(Comprehensive Perl Archive Network)。
Perl的特色
    1.簡單。解決一個通常的問題用它幾行代碼就完成了. 一個稍複雜一點的問題代碼也不會超過一屏!
    2.可移植性強。幾乎能夠在任何地方任何操做系統運行。
    3.幾乎不受限制。小程序大程序都適合用perl編寫。數組和哈希等沒有最大限制,你能夠將內存填滿。
    4.速度很快。由於是開源的語言,全部的開發者同時也是用戶。
    5.難以閱讀。Perl的靈活性和「過分」的冗餘語法,也所以得到了write-only的「美譽」,由於許多Perl
      程序的代碼使人難以閱讀,實現相同功能的程序代碼長度能夠相差十倍百倍。但Perl一樣能夠將代碼
      書寫得像Python或Ruby等語言同樣優雅。
Perl適合作的事情
    1.合適在三分鐘內寫出「急功近利」的小程序,也能夠編寫用處普遍須要不少人完成的大型程序。
    2.擅長處理文字。約有90%與文字處理有關。
Perl語法(perl是從上到下執行的)
    1.標量。也稱變量,以$開頭,包含數字和字符串,二者能夠相互轉換。注:單引號中的字符串表示它自己;雙引號中若是有反斜線或八進制十六進制寫法,表示轉換後字符。mysql

變量定義:my $abc=123;
    2.列表和數組。數組以@開頭,如@fred=(1,2,3),數組中的元素用@fred[0],@fred[1]表示。perl支持數組內插,例如:
@rock=qw{stone slate rubble};
pint "quartz @rock limestone";#輸出五種以空白隔開的石頭。
    3.Perl的「老地方」:$_。當語句中省略變量名稱的時候,系統會自動使用它的「老地方」變量。例如讀文件的每一行,默認都是$_;
    4.子程序。一般以&開頭,可省略但最好別省略。相似於方法。
    sub marine {
    $n+=1;
    pint "Hello,sailor number $n!\n";
    }
    子程序一般狀況下是全局的,能夠放在程序的任意位置,且不須要事先聲明。若是定義了兩個相同名稱的子程序,後面一個會覆蓋前一個。能夠在任意表達式中調用子程序 &marine。全部的子程序都有返回值,返回值便是最後一次的運算結果。
    另外,子程序能夠帶參數,參數存在數組變量@_中,該變量在子程序執行期間有效,按順序依次爲$_[0],$_[1]。
    默認狀況下,全部的變量都是全局變量,子程序中(其餘任何語句塊如foreach、if一樣)也能夠變量私有,my($m,$n)。注:my在不加括號是,表示私有化單個變量 my $fred,也能夠私有化數組  my @phone
Perl的著名特性:哈希
    所謂哈希就是一種數據結構,和數組的相同之處在於:能夠容納不少值(沒有上限),並能隨即存取;而區別在於:不像數組是以數字來檢索,哈希是以名字來檢索。也就是說,檢索用的鍵不是數字,而是保證惟一的字符串。哈希裏沒有順序,只有一些鍵/值對。perl在鍵/值對增多時並不會變慢
    哈希的應用:
    1.按名字找姓;
    2.用主機名找IP地址;
    3.按單詞統計出現次數;
    4.按駕駛執照號找出姓名。
    哈希的使用:
    1.給哈希賦值:%any_hash=("a"=>1,"b"=>23,"c"=>543)
    2.訪問哈希:$family_name{"fred"}
    3.訪問整個哈希:�mily_name
    4.哈希鬆綁:@any_arry=%some_hash
    5.創建反轉哈希:%inverse_hash=reverse %any_hash正則表達式

----------讀文件賦值給hash-----------sql


sub readUid2Mobile()
{
    my($uid,$mobile);
    if(-e $uid2mobileFile)
    {
        open (FP, "$uid2mobileFile") || return -1;
        while(<FP>)
        {shell

            chomp;#去除行末尾換行
            ($uid,$mobile) =split(/\t/)#以\t分隔
            $uidMobile{$uid} = $mobile;#往hash裏賦值
        }
        close FP;
    }數據庫

}小程序

Perl另外一特點:對正則表達式強有力的支持
    因爲Perl的主要功能是處理文字,正則表達式在這裏起到關鍵做用,本文暫不作介紹,之後單獨一個篇幅介紹。
Perl的控制結構
1.if 判斷
    if ($name gt 'fred'){
    print "'$name' comes after 'fred' in sorted order.\n";
    }else{
    print "'$name' does not comes after 'fred'.\n"
    }
2.while:循環
    $count = 0;
    while ($count<10){
    $count +=2;
    print "count is now $count\n";
    }
3.foreach:遍歷數組中的值
    foreach $rock (qw/bedrock slate lava/){
    print "one rock is $rock.\n";
    }數組

my @mobilelist = qw(13800000001 18700000001);
	foreach (@mobilelist){
		my $mobile = $_;
		print "$mobile\n";
		#system($sendAlarmcmd); 執行系統命令
	}


4.其餘:unless,until,for等等
Perl模塊
Perl模塊有兩種來源:一是隨Perl發行版本一同打包的;另外一種須要用CPAN下載。(CPAN網站:
http:search.cpan.org)
1.手動安裝模塊
    perl Makefile.PL;
    make install;
若是沒有權限安裝模塊到全局目錄,則能夠在Makefile.PL後面加上PREFIX參數,以下:
    perl Makefile.PL PREFIX=/Users/fred/lib;
有些Perl模塊的開發者會要求使用另外一個輔助模塊Module::Build來編譯並安裝他們的做品。此時安裝的
方式大體以下:
    perl Build.PL;
    ./Build install;
2.使用CPAN模塊自動安裝:
在命令行啓動CPAN.pm,在其中運行相關模塊的維護命令:
  perl -MCPAN -e shell;
另外一種更簡單的方法:
    cpan Module::CoreList LWP CGI::Prototype;
CoreList爲想安裝的模塊名稱列表
3.使用簡單模塊
以取得basename爲例
    use File::Basename;
    my $name="/usr/local/bin/perl";
    my $basename=basename $name;    #返回'perl'
有時候引入的模塊中有與本身寫的子程序相同的函數名,爲避免此衝突,只需在File::Basename的use聲
明中,加上導入列表來指明它提供哪些函數。
    use File::Basename qw/ basename /;
    use File::Basename qw/ /;    #表示徹底不需求引入任何函數
    use File::Basename();        #同上,簡寫
作完以上聲明以後,能夠經過全名的方式調用相應的函數
    use File::Basename qw/ /;
    my $name="/usr/local/bin/perl";
    my $dirname=File::Basename::direname $name;   
File::Spec模塊
File::Spec是面向對象的模塊,調用其中的方法,方式以下:
    use File::spec;
    my $new_name = File::Spec->catfile($dirname,$basename);  #模塊名稱+瘦箭頭+方法名稱
    rename($old_name,$new_name) or warn "Can't rename '$old_name' to '$new_name':$!";
DBI模塊
    use DBI;
    $dbh = DBI->connect($data_source,$username,$password);    #鏈接數據庫
    $sth = $dbh->prepare("select * from foo where bla");      #準備查詢
    $sth ->execute();
    @row_ary = $sth->fetchrow_array;
    $sth->finish
    $dbh->disconnect();    #斷開數據庫鏈接數據結構

sub connectDB
{
	print "start connect!\n";
 	while(!defined ($DB = DBI->connect("DBI:mysql:$Database:$dbIP", "$loginname", "$password"))){
  		sleep(1);
    	print STDERR "Couldn't connect the mysql database xx and try it again.\n";
  	}   
   print "end connect !\n";
}

---------------------代碼塊---------------------------less

文件頭:函數

use strict; #嚴格檢查語法
use Time::Local;#時間
use POSIX qw(strftime);
use Getopt::Std;
use Net::FTP;
use DBI;#數據庫
use MIME::Base64;
use Time::HiRes qw(gettimeofday);

 

計算時間差:

my($start_sec, $start_usec)=gettimeofday();
doSomething($param);
my($end_sec, $end_usec)=gettimeofday();
my $times_use = ($end_sec - $start_sec)*1000000+($end_usec - $start_usec);

FTP下載:

$ftp = Net::FTP->new("$ftpIP", Timeout => 10) or next;
		$ftp->login($user,$passwd) or next;
		$ftp->ascii;

		$ret = fileDown($ftp, $show);#文件下載
		$ftp->quit;
sub fileDown()
{
	my ($ftp, $toDir, $cnum) = @_;

   my ($curDir, $file,$downfile,$cmd, $pos, $fileNamePre);
   $downfile = $toDir."/Data";
   $ftp->cwd($downfile) or return -1;
   $curDir = $ftp->pwd;
   $fileNamePre="a_9101_".$toDir."_".$tdatetime;

   my @allfiles = $ftp->ls() or return 0;
   foreach (@allfiles)
   {
        $file=$_;
		$pos = -1;
		if( index($file, $fileNamePre)==0 && index($file, ".dat")>0 )#搜索.dat文件
		{
			$ftp->get($file);
			$cmd = "mv $file ftpdata/".$cnum."_".$file;#下載文件移到固定文件夾下
			system($cmd);
		}
   }
	$ftp->cwd("../..");#不知道這句是要幹什麼用
	return 1;
}
#!/usr/bin/perl -w
#轉載簡單使用
use Net::FTP;

$server = '192.168.1.251';
$port = '9999';
$user = 'user';
$pw = '123456';

$ftp = Net::FTP->new($server, Port=>$port, Debug => 0, Timeout => 600) or die "Cannot connect.\n";
$ftp->login($user, $pw) or die "Could not login.\n";
$ftp->cwd('/opt/ftp/123') or die "Cannot change working directory.\n";

$remotefile = '123456.mp3';
$localpath = '/usr/local/src';
$localfile = $localpath . "/1234567890.mp3";

$ftp->get($remotefile, $localfile) or die "Could not get remotefile:$remotefile.\n";
print "get file sucessful.\n";

$ftp->quit;

獲取時間:

sub GetTTime
{
	my $days = (defined $_[0]?$_[0]:0);
	$days = ($days*24*60*60);
	my ($year, $month, $day);
	my @array_date;
	@array_date = localtime(time-$days);
	$year = 1900+$array_date[5];
	$month = $array_date[4] +1;
	if ($month <= 9) {
		$month= '0'.$month;
	}
	$day = $array_date[3];
	if ($day <= 9) {
		$day = '0'.$day;
	}
	return ($year, $month, $day);
}

判斷文件是否存在

sub IsExecOrNot()
{
	my $date = $_[0];
	my $datefile = "../log/test_$date.log";
	my ($ret, $touchfilecmd, $LOG);
	$touchfilecmd = "touch $datefile";

	$ret = open($LOG, $datefile);
	if ($ret){
		writelog("open $datefile OK, the script is execed!\n");
		close(LOG);
		exit;
	}
	else{
		writelog("open $datefile error, the script isn't execed!\n");
		system($touchfilecmd);
	}
}
相關文章
相關標籤/搜索