Perl 模块(一)

来源:互联网 发布:c语言苹果分级 编辑:程序博客网 时间:2024/05/16 07:31
  1. (1) Net::FTP  
  2. (2) Net::Telnet  
  3. (3) LWP::Simple, get()  
  4. (4) Expect  
  5. (5) XML::Simple, XMLin()  
  6. (6) Data::Dumper, Dumper()  
  7. (7) IO::Socket  
  8. (8) Date::Manip, DateCalc(), UnixDate()  
  9. (9) Date::Manip, Date_Cmp()  
  10. (10) File::Find, find()  
  11. (11) ExtUtils::Installed, new(), modules(), version()  
  12. (12) DBI, connect(), prepare(), execute(), fetchrow_array()  
  13. (13) Getopt::Std  
  14. (14) Proc::ProcessTable  
  15. (15) Shell  
  16. (16) Time::HiRes, sleep(), time()  
  17. (17) HTML::LinkExtor, links(), parse_file()  
  18. (18) Net::Telnet, open(), print(), getline()  
  19. (19) Compress::Zlib, gzopen(), gzreadline(), gzclose()  
  20. (20) Net::POP3, login(), list(), get()  
  21. (21) Term::ANSIColor  
  22. (22) Date::Calc Calendar(), Today()  
  23. (23) Term::Cap, Tgetend(), Tgoto, Tputs()  
  24. (24) HTTPD::Log::Filter  
  25. (25) Net::LDAP  
  26. (26) Net::SMTP mail(), to(), data(), datasend(), auth()  
  27. (27) MIME::Base64, encode_base64(), decode_base64()  
  28. (28) Net::IMAP::Simple, login(), mailboxes(), select(), get()...  
  29. (29) Bio::DB::GenBank, Bio::SeqIO  
  30. (30) Spreadsheet::ParseExcel  
  31. (31) Text::CSV_XS, parse(), fields(), error_input()  
  32. (32) Benchmark  
  33. (33) HTTP:: Daemon, accept(), get_request()...  
  34. (34) Array::Compare, compare(), full_compare()...  
  35. (35) Algorithm::Diff, diff()  
  36. (36) List::Util, max(), min(), sum(), maxstr(), minstr()...  
  37. (37) HTML::Parser  
  38. (38) Mail::Sender  
  39. (39) Time::HiRes, gettimeofday(), usleep()  
  40. (40) Image::Magick  
  41. (41) Data::SearchReplace  
  42.   
  43.   
  44.   
  45. (1) Net::FTP  
  46.   
  47. #!/usr/bin/perl -w  
  48. # file: ftp_recent.pl  
  49. # Figure 6.1: Downloading a single file with Net::FTP  
  50. use Net::FTP;  
  51.   
  52. use constant HOST => 'ftp.perl.org';  
  53. use constant DIR => '/pub/CPAN';  
  54. use constant FILE => 'RECENT';  
  55.   
  56. my $ftp = Net::FTP->new(HOST) or die "Couldn't connect: $@\n";  
  57. $ftp->login('anonymous') or die $ftp->message;  
  58. $ftp->cwd(DIR) or die $ftp->message;  
  59. $ftp->get(FILE) or die $ftp->message;  
  60. $ftp->quit;  
  61.   
  62. warn "File retrieved successfully.\n";  
  63.   
  64.   
  65.   
  66.   
  67. (2) Net::Telnet  
  68.   
  69. #!/usr/bin/perl -w  
  70. # file:remoteps.pl  
  71.   
  72. use strict;  
  73. use Net::Telnet;  
  74. use constant HOST => 'phage.cshl.org';  
  75. use constant USER => 'lstein';  
  76. use constant PASS => 'xyzzy';  
  77.   
  78. my $telnet=Net::Telnet->new(HOST);  
  79. $telnet->login(USER,PASS);  
  80. my @lines=$telnet->cmd('ps -ef');  
  81. print @lines;  
  82.   
  83.   
  84. (3) LWP::Simple, get()  
  85.   
  86. #!/usr/bin/perl -w  
  87. use strict;  
  88. use LWP::Simple qw(get);  
  89.   
  90. my $url = shift || "http://www.chinaunix.net";  
  91. my $content = get($url);  
  92.   
  93. print $content;  
  94.   
  95. exit 0;  
  96. #最简单方便的get网页的方法。  
  97.   
  98.   
  99. (4) Expect  
  100.   
  101. #!/usr/bin/perl  
  102. use strict;  
  103. use Expect;  
  104.   
  105. my $timeout = 2;  
  106. my $delay = 1;  
  107. my $cmd = "ssh";  
  108. my @params = qw/202.108.xx.xx -lusername -p22/;  
  109. my $pass = "passwd";  
  110.   
  111. my $exp = Expect->spawn($cmd, @params) or die "Can't spawn $cmd\n";  
  112. $exp->expect($timeout, -re=>'[Pp]assword:');  
  113. $exp->send_slow($delay, "$pass\r\n");  
  114.   
  115. $exp->interact();  
  116. $exp->hard_close();  
  117.   
  118. exit 0;  
  119.   
  120.   
  121. (5) XML::Simple, XMLin()  
  122.   
  123. #!/usr/bin/perl -w  
  124. use strict;  
  125. use XML::Simple;  
  126. my $text = <<xml;  
  127. < ?xml version="1.0"? >  
  128. <web-app>  
  129. <servlet>  
  130. <servlet-name>php</servlet-name>  
  131. <servlet-class>net.php.servlet</servlet-class>  
  132. </servlet>  
  133. <servlet-mapping>  
  134. <servlet-name>php</servlet-name>  
  135. <url-pattern>*.php</url-pattern>  
  136. </servlet-mapping>  
  137. </web-app>  
  138. xml  
  139. my $x = XMLin($text);  
  140. foreach my $tag(keys %$x)  
  141. {  
  142. my %h = %{$$x{$tag}};  
  143. foreach(keys %h)  
  144. {  
  145. print "$tag => ";  
  146. print "$_ => $h{$_}\n";  
  147. }  
  148. }  
  149. exit 0;  
  150.   
  151.   
  152. (6) Data::Dumper, Dumper()  
  153.   
  154. #!/usr/bin/perl -w  
  155. use strict;  
  156. use Data::Dumper;  
  157.   
  158. print Dumper(@INC);  
  159. print Dumper(%ENV);  
  160. exit 0;  
  161.   
  162.   
  163. (7) IO::Socket  
  164.   
  165. #!/usr/bin/perl -w  
  166. use strict;  
  167. use IO::Socket;  
  168.   
  169. my $host = "www.chinaunix.net";  
  170. my $port = "80";  
  171. my $http_head = "GET / HTTP/1.0\nHost: $host:$port\n\n";  
  172. my $sock = IO::Socket::INET->new("$host:$port")  
  173. or die "Socket() error, Reason : $! \n";  
  174.   
  175. print $sock $http_head;  
  176. print <$sock>;  
  177.   
  178. exit 0;  
  179.   
  180.   
  181. (8) Date::Manip, DateCalc(), UnixDate()  
  182.   
  183. #!/usr/bin/perl  
  184. use strict;  
  185. use Date::Manip;  
  186. my $date1 = "Fri Jun 6 18:31:42 GMT 2003";  
  187. my $date2 = "2003/05/06";  
  188. my $flag=&Date_Cmp($date1,$date2);  
  189.   
  190. if($flag<0)  
  191. {  
  192. print "date1 is earlier!\n";  
  193. }  
  194. elsif($flag==0)  
  195. {  
  196. print "the two dates are identical!\n";  
  197. }  
  198. else  
  199. {  
  200. print "date2 is earlier!\n";  
  201. }  
  202. exit 0;  
  203.   
  204.   
  205. (9) Date::Manip, Date_Cmp()  
  206.   
  207.   
  208.   
  209. (10) File::Find, find()  
  210.   
  211.   
  212. #!/usr/bin/perl -w  
  213. use strict;  
  214. use File::Find;  
  215.   
  216. my $file = "access.log";  
  217. my $path = "/";  
  218.   
  219. find(&process, $path);  
  220.   
  221. sub process{ print $File::Find::dir, "$_\n" if(/$file/); }  
  222.   
  223. exit 0;  
  224.   
  225. #用于在unix文件树结构中查找对象。  
  226.   
  227. (11) ExtUtils::Installed, new(), modules(), version()  
  228.   
  229. #!/usr/bin/perl  
  230. use strict;  
  231. use ExtUtils::Installed;  
  232.   
  233. my $inst= ExtUtils::Installed->new();  
  234. my @modules = $inst->modules();  
  235.   
  236. foreach(@modules)  
  237. {  
  238. my $ver = $inst->version($_) || "???";  
  239. printf("%-12s -- %s\n", $_, $ver);  
  240. }  
  241. exit 0;  
  242.   
  243.   
  244. (12) DBI, connect(), prepare(), execute(), fetchrow_array()  
  245.   
  246. #!/usr/bin/perl  
  247. use strict;  
  248. use DBI;  
  249.   
  250. my $dbh = DBI->connect("dbi:mysql:dbname", 'user','passwd', '')  
  251. or die "can't connect!\n";  
  252. my $sql = qq/show variables/;  
  253. my $sth = $dbh->prepare($sql);  
  254. $sth->execute();  
  255.   
  256. while(my @array=$sth->fetchrow_array())  
  257. {  
  258. printf("%-35s", $_) foreach(@array);  
  259. print "\n";  
  260. }  
  261. $dbh -> disconnect();  
  262. exit 0;  
  263.   
  264.   
  265.   
  266. (13) Getopt::Std  
  267.   
  268. #!/usr/bin/perl  
  269. use strict;  
  270. use Getopt::Std;  
  271.   
  272. my %opts;  
  273. getopts("c:hv", %opts);  
  274.   
  275. foreach(keys %opts)  
  276. {  
  277. /c/ && print "welcome to ", $opts{$_} || "ChinaUnix", "!\n";  
  278. /h/ && print "Usage : $0 -[hv] -[c msg] \n";  
  279. /v/ && print "This is demo, version 0.001.001 built for $^O\n";  
  280. }  
  281. exit 0;  
  282.   
  283.   
  284. (14) Proc::ProcessTable  
  285.   
  286. #直接访问Unix进程表,类似ps command。  
  287.   
  288. #!/usr/bin/perl  
  289. use strict;  
  290. use Proc::ProcessTable;  
  291.   
  292. my $pt = new Proc::ProcessTable;  
  293.   
  294. foreach(reverse sort @{$pt->table})  
  295. {  
  296. print $_->pid, " => ";  
  297. print $_->cmndline, "\n";  
  298. }  
  299. exit 0;  
  300.   
  301.   
  302. (15) Shell  
  303.   
  304. #!/usr/bin/perl  
  305. use strict;  
  306. use Shell;  
  307.   
  308. print "now is : ", date();  
  309. print "current time is : ", date("+%T");  
  310.   
  311. my @dirs = ls("-laF");  
  312. foreach(@dirs)  
  313. {  
  314. print if(//$/);#print directory  
  315. }  
  316. exit 0;  
  317.   
  318. #Shell命令直接做为函数,在Perl中调用。  
  319.   
  320.   
  321. (16) Time::HiRes, sleep(), time()  
  322.   
  323. #!/usr/bin/perl  
  324. #Another use of Time::HiRes Module.  
  325.   
  326. use strict;  
  327. use Time::HiRes qw(sleep time);  
  328.   
  329. $| = 1;  
  330. my $before = time;  
  331. for my $i (1..100)  
  332. {  
  333. print "$i\n";  
  334. sleep(0.01);  
  335. }  
  336. printf("time used : %.5f seconds\n", time - $before);  
  337. exit 0;  
  338.   
  339. use Time::HiRes后,此模块提供sleep(), alarm(), time()的增强版以  
  340. 取代perl内置的相应函数。  
  341. 其中sleep()和alarm()的参数可以是小数。比如sleep(0.1)表示休眠0.1秒,  
  342. time()可以返回浮点数。  
  343.   
  344.   
  345. (17) HTML::LinkExtor, links(), parse_file()  
  346.   
  347. #!/usr/bin/perl  
  348. use strict;  
  349. use HTML::LinkExtor;  
  350.   
  351. my $p = new HTML::LinkExtor;  
  352. $p->parse_file(*DATA);  
  353.   
  354. foreach my $links ($p->links())  
  355. {  
  356. map {print "$_ "} @{$links};  
  357. print "\n";  
  358. }  
  359. exit 0;  
  360.   
  361. __DATA__  
  362.   
  363. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 Strict//EN"  
  364. "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">  
  365. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">  
  366. <head>  
  367. <meta http-equiv="Content-Type" content="text/html"/>  
  368. <title>CPAN</title>  
  369. <!-- Copyright Jarkko Hietaniemi <jhi@iki.fi> 1998-2002  
  370. All Rights Reserved.  
  371. The CPAN Logo provided by J.C. Thorpe.  
  372. You may distribute this document either under the Artistic License  
  373. (comes with Perl) or the GNU Public License, whichever suits you.  
  374.   
  375. You are not allowed to remove or alter these comments. -->  
  376. <!-- $Id: cpan-index.html,v 1.7 2003/02/17 10:23:46 jhi Exp $ -->  
  377. <link rev="made" href="mailto:cpan@perl.org"></link>  
  378. <style type="text/css">  
  379. <!--  
  380.   
  381. body{  
  382. color:black;  
  383. background:white;  
  384. margin-left:2%;  
  385. margin-right:2%;  
  386. }  
  387.   
  388. h1{  
  389. text-align:center;  
  390. }  
  391.   
  392. img {  
  393. vertical-align: 50%;  
  394. border: 0;  
  395. }  
  396.   
  397. .left{  
  398. text-align:left;  
  399. float:none;  
  400. }  
  401.   
  402. .center{  
  403. text-align:center;  
  404. float:none;  
  405. }  
  406.   
  407. .right{  
  408. text-align:right;  
  409. float:none;  
  410. }  
  411.   
  412. -->  
  413. </style>  
  414. </head>  
  415. <body>  
  416.   
  417. <table width="100%">  
  418. <tr>  
  419. <td rowspan="2">  
  420. <div class="left">  
  421. <img src="misc/jpg/cpan.jpg"  
  422. alt="[CPAN Logo]" height="121" width="250"/>  
  423. </div>  
  424. </td>  
  425. <td>  
  426. <div class="right">  
  427. <h1><a id="top">Comprehensive Perl Archive Network</a></h1>  
  428. </div>  
  429. </td>  
  430. </tr>  
  431. <tr>  
  432. <td>  
  433. <div class="center">  
  434. 2003-06-10 online since 1995-10-26<br/>1662 MB 246 mirrors<br/>2903 authors 4767 modules  
  435. </div>  
  436. </td>  
  437. </tr>  
  438. <tr>  
  439. <td colspan="2">  
  440. <p class="left">  
  441. Welcome to CPAN! Here you will find All Things Perl.  
  442. </p>  
  443. </td>  
  444. <td>  
  445. </td>  
  446. </tr>  
  447. </table>  
  448.   
  449. <hr/>  
  450.   
  451. <table width="100%">  
  452.   
  453. <tr>  
  454.   
  455. <td>  
  456.   
  457. <h1>Browsing</h1>  
  458. <ul>  
  459. <li><a href="modules/index.html">Perl modules</a></li>  
  460. <li><a href="scripts/index.html">Perl scripts</a></li>  
  461. <li><a href="ports/index.html">Perl binary distributions ("ports")</a></li>  
  462. <li><a href="src/README.html">Perl source code</a></li>  
  463. <li><a href="RECENT.html">Perl recent arrivals</a></li>  
  464. <li><a href="http://search.cpan.org/recent">recent</a> Perl modules</li>  
  465. <li><a href="SITES.html">CPAN _fcksavedurl=""SITES.html">CPAN" sites</a> list</li>  
  466. <li><a href="http://mirrors.cpan.org/">CPAN sites</a> map</li>  
  467. </ul>  
  468.   
  469. </td>  
  470.   
  471. <td>  
  472.   
  473. <h1>Searching</h1>  
  474.   
  475. <ul>  
  476. <li><a href="http://kobesearch.cpan.org/">Perl core and CPAN modules documentation </a> (Randy Kobes)</li>  
  477. <li><a href="http://www.perldoc.com/">Perl core documentation</a> (Carlos Ramirez)</li>  
  478. <li><a href="http://search.cpan.org/">CPAN modules, distributions, and authors</a> (search.cpan.org)</li>  
  479. <li><a href="http://wait.cpan.org/">CPAN modules documentation</a> (Ulrich Pfeifer)</li>  
  480. </ul>  
  481.   
  482. <h1>FAQ etc</h1>  
  483.   
  484. <ul>  
  485. <li><a href="misc/cpan-faq.html">CPAN Frequently Asked Questions</a></li>  
  486. <li><a href="http://lists.cpan.org/">Perl Mailing Lists</a></li>  
  487. <li><a href="http://bookmarks.cpan.org/">Perl Bookmarks</a></li>  
  488. </ul>  
  489.   
  490. <p><small>  
  491. Yours Eclectically, The Self-Appointed Master Librarian (OOK!) of the CPAN<br/>  
  492. <i>Jarkko Hietaniemi</i>  
  493. <a href="mailto:cpan@perl.org">cpan@perl.org</a>  
  494. <a href="disclaimer.html">[Disclaimer]</a> _fcksavedurl=""disclaimer.html">[Disclaimer]</a>"  
  495. </small>  
  496. </p>  
  497.   
  498. </td>  
  499.   
  500. </tr>  
  501.   
  502. </table>  
  503.   
  504. <hr/>  
  505.   
  506. <table width="100%">  
  507. <tr>  
  508.   
  509. <td>  
  510. <div class="left">  
  511. <a href="http://validator.w3.org/check?uri=http%3A%2F%2Fwww.cpan.org%2Findex.html">  
  512. <img src="misc/gif/valid-xhtml10.gif" alt="Valid XHTML 1.0!" height="31" width="88"/></a>  
  513. <a href="http://jigsaw.w3.org/css-validator/validator?uri=http%3A%2F%2Fwww.cpan.org%2Findex.html">  
  514. <img src="misc/gif/vcss.gif" alt="[Valid CSS]" height="31" width="88"/></a>  
  515. </div>  
  516. </td>  
  517. <td>  
  518. <div class="right">  
  519.   
  520. <table width="100%">  
  521.   
  522. <tr>  
  523. <td class="right">  
  524. <small>  
  525. CPAN master site hosted by  
  526. </small>  
  527. </td>  
  528. </tr>  
  529. <tr>  
  530. <td class="right">  
  531. <a href="http://www.csc.fi/suomi/funet/verkko.html.en/"><img src="misc/gif/funet.gif" alt="FUNET" height="25" width="88"/></a>  
  532. </td>  
  533. </tr>  
  534. </table>  
  535.   
  536. </div>  
  537. </td>  
  538.   
  539. </tr>  
  540. </table>  
  541.   
  542. </body>  
  543. </html>  
  544.   
  545.   
  546. (18) Net::Telnet, open(), print(), getline()  
  547.   
  548. #!/usr/bin/perl  
  549. use strict;  
  550. use Net::Telnet;  
  551.   
  552. my $p = Net::Telnet->new();  
  553. my $h = shift || "www.chinaunix.net";  
  554.   
  555. $p->open(Host => $h, Port => 80);  
  556. $p->print("GET /\n");  
  557. while(my $line = $p->getline())  
  558. {  
  559. print $line;  
  560. }  
  561. exit 0;  
  562.   
  563.   
  564. (19) Compress::Zlib, gzopen(), gzreadline(), gzclose()  
  565.   
  566. #!/usr/bin/perl  
  567. use strict;  
  568. use Compress::Zlib;  
  569.   
  570. my $gz = gzopen("a.gz", "rb");  
  571.   
  572. while( $gz->gzreadline(my $line) > 0 )  
  573. {  
  574. chomp $line;  
  575. print "$line\n";  
  576. }  
  577.   
  578. $gz->gzclose();  
  579. exit 0;  
  580.   
  581. #直接使用shell的zmore, zless, zcat打开文件也不错,但是如果gz文件很大,还是应该选择zlib。  
  582.   
  583.   
  584. (20) Net::POP3, login(), list(), get()  
  585.   
  586. #!/usr/bin/perl  
  587. use strict;  
  588. use Net::POP3;  
  589. use Data::Dumper;  
  590.   
  591. my $user = "user";  
  592. my $pass = shift or die "Usage : $0 passwd\n";  
  593. my $host = "pop3.web.com";#pop3 address  
  594.   
  595. my $p = Net::POP3->new($host) or die "Can't connect $host!\n";  
  596. $p->login($user, $pass) or die "user or passwd error!\n";  
  597. my $title = $p->list or die "No mail for $user\n";  
  598.   
  599. foreach my $h(keys %$title)  
  600. {  
  601. my $msg = $p->get($h);  
  602. print @$msg;  
  603. }  
  604. $p->quit;  
  605. exit 0;  
  606.   
  607. telnet pop3.web.com 110 也可以直接连到pop3 server上,然后通过pop3命令与邮件服务器交互,  
  608.   
  609. 简单的命令有:  
  610.   
  611. QUOTE:USER name  
  612. PASS string  
  613. STAT  
  614. LIST [n]  
  615. RETR msg  
  616. DELE msg  
  617. NOOP  
  618. RSET  
  619. QUIT  
  620.   
  621.   
  622. 有兴趣的朋友可以试一试。  
  623. 这样,也就可以利用Net::Telnet来做一个收信件的简单程序。  
  624.   
  625.   
  626.   
  627. (21) Term::ANSIColor  
  628.   
  629. #!/usr/bin/perl  
  630. use strict;  
  631. use Term::ANSIColor qw(:constants);  
  632.   
  633. $Term::ANSIColor::AUTORESET = 1;  
  634.   
  635. $| = 1;  
  636. my $str = "Welcome to chinaunix ^_^!\n";  
  637.   
  638. for my $i(0..length($str)-1)  
  639. {  
  640. print BOLD RED substr($str, $i, 1);  
  641. select(undef, undef, undef, 0.3);  
  642. }  
  643. exit 0;  
  644.   
  645. 查看ANSIColor.pm可以得知作者是利用ANSI转义序列,改变终端字符颜色的。  
  646. print "\e[34m\n";  
  647. 即是改变前景色为blue;  
  648.   
  649. shell命令为echo -e "\033[31m";#改变前景色为红色。  
  650. (freeBSD,Solaris下此命令测试OK)  
  651.   
  652.   
  653. #!/usr/bin/perl  
  654. use strict;  
  655. use Term::ANSIColor qw(:constants);  
  656.   
  657. $Term::ANSIColor::AUTORESET = 1;  
  658.   
  659. $| = 1;  
  660.   
  661. print "\e[20;40H";  
  662. my $str = "Welcome to chinaunix ^_^!\n";  
  663.   
  664. print BOLD BLINK $str;  
  665. exit 0;  
  666.   
  667.   
  668. 转义序列echo -e "\033[20;40H";可以改变光标位置。  
  669. perl中就可以:print "\e[20;40H";  
  670.   
  671.   
  672. (22) Date::Calc Calendar(), Today()  
  673.   
  674. #!/usr/bin/perl  
  675. use strict;  
  676. use Date::Calc qw(Calendar Today);  
  677.   
  678. my $year = "2003";  
  679. my $month = "6";  
  680. my $day;  
  681.   
  682. my $cal = Calendar($year, $month);  
  683. (undef, undef, $day) = Today();  
  684.   
  685. $cal =~ s/$day/e[5me[31m$daye[0m/;  
  686.   
  687. print $cal;  
  688. exit 0;  
  689.   
  690. 本例子打印出一个2003年6月份的日历,当天日期用红色的闪烁数字表示。  
  691.   
  692. Date::Calc提供了时间日期计算的另一种方式(一种是Date::Manip),  
  693. 大量简单方便的方法(函数)供使用者调用。  
  694.   
  695. 在例子中的年和月我是自己指定的,也可以  
  696. ($year, $month, $day) = Today();  
  697.   
  698. 颜色和闪烁是用ANSI escape sequences。  
  699. 详细说明尽在ANSIColor.pm source和perldoc Term::ANSIColor里。  
  700. (perldoc Term::ANSIColor其实也在ANSIColor.pm source里) :)  
  701.   
  702.   
  703.   
  704.   
  705. (23) Term::Cap, Tgetend(), Tgoto, Tputs()  
  706.   
  707. #!/usr/bin/perl  
  708. use strict;  
  709. use Term::Cap;  
  710.   
  711. $| = 1;  
  712. my $i = 1;  
  713. my $flag = 0;  
  714.   
  715. my $tcap = Term::Cap->Tgetent({TERM => undef, OSPEED => 1});  
  716. $tcap->Tputs('cl', 1, *STDOUT);#clear screen  
  717.   
  718. while($i)  
  719. {  
  720. if($i > 50 || $flag == 1)  
  721. {  
  722. $i --;  
  723. $flag = 1;  
  724. $flag = 0 if($i == 1);  
  725. }  
  726. else  
  727. {  
  728. $i ++;  
  729. $flag = 0;  
  730. }  
  731.   
  732. $tcap->Tgoto('cm', $i, 15, *STDOUT);#move cursor  
  733. print " welcome to chinaunix! ";  
  734. select(undef, undef, undef, 0.02);  
  735. }  
  736. exit 0;  
  737.   
  738. Term::Cap 终端控制模块。  
  739. 代码效果:一个左右移动的字串 "welcome to chinaunix! " :)  
  740.   
  741.   
  742.   
  743. (24) HTTPD::Log::Filter  
  744.   
  745. #!/usr/bin/perl  
  746. use strict;  
  747. use HTTPD::Log::Filter;  
  748.   
  749. my $filter = HTTPD::Log::Filter->new(format => "CLF",  
  750. capture => ['request', 'host']);  
  751.   
  752. foreach(`cat access_log`)  
  753. {  
  754. chomp;  
  755. unless( $filter->filter($_) )  
  756. {  
  757. print "[$_]\n";  
  758. next;  
  759. }  
  760. print $filter->request, "\n";  
  761. }  
  762. exit 0;  
  763.   
  764. 如果我们工作中经常需要分析Apache日志,这个模块可以提供一些方便。  
  765. 创建对象实例以后,用filter方法来过滤,没有正确匹配的行将返回false,  
  766. 然后用相应的方法print出我们需要的数据。(host,request,date...等等方法,  
  767. 由capture选项以参数引入)  
  768. 可以用re方法打印出作者所使用的匹配模式:  
  769.   
  770.   
  771.   
  772. QUOTE:use HTTPD::Log::Filter;  
  773. print HTTPD::Log::Filter->new(format=>"CLF",capture=>['request'])->re;  
  774.   
  775.   
  776. 详见perldoc HTTPD::Log::Filter. enjoy it  
  777.   
  778.   
  779.   
  780. (25) Net::LDAP  
  781.   
  782. #!/usr/bin/perl  
  783. use Net::LDAP;  
  784.   
  785. ## get a object of ldap  
  786. $ldap = Net::LDAP->new("1.1.1.1", port =>"389", version => 3) or die "$@";  
  787. # object of Net::LDAP::Message  
  788. $mesg = $ldap->bind($_cer_id, password => $_cer_pw); # 查詢用的ID/PASSWD  
  789. if($mesg->is_error) {die $mesg->error;}  
  790. $mesg = $ldap->search(  
  791. base => "o=abc,c=tt", # 起始點  
  792. scope => "sub", # 範圍  
  793. filter => "(uid=apile)", # 條件  
  794. attrs => ["cn"], # 要取得的attribute  
  795. typesonly => 0 );  
  796.   
  797. my $max_len = $mesg->count; ## get number of entry  
  798.   
  799. #--取得中文姓名,可能不只一筆  
  800. for($i=0;$i<$max_len;$i++){  
  801. $entry = $mesg->entry($i);  
  802. $cname = $entry->get_value("cn"); # get chinese name  
  803. }  
  804.   
  805. #--作密碼認證  
  806. $mesg = $ldap->bind($entry->dn, password => "abc", version => 3)  
  807. ||die "can't connect to ldap";  
  808. if($mesg->code) { print "verification is failed"}  
  809. else{ print "success"}  
  810.   
  811.   
  812. LDAP version 3..可以用于查询基本资料、验证密码之用..  
  813.   
  814.   
  815. (26) Net::SMTP mail(), to(), data(), datasend(), auth()  
  816.   
  817. #!/usr/bin/perl  
  818.   
  819. use strict;  
  820. use Net::SMTP;  
  821.   
  822. my $smtp = Net::SMTP->new('smtp.sohu.com', Timeout => 10, Debug => 0)  
  823. or die "new error\n";  
  824. #$smtp->auth("user", "passwd") or die "auth error\n";  
  825. $smtp->mail('some');  
  826. $smtp->to('some@some.com');  
  827. $smtp->data("chinaunix,哈楼你好啊!\n:)");  
  828. $smtp->quit;  
  829.   
  830. exit 0;  
  831.   
  832.   
  833. 有的SMPT Server需要Authentication,那么就使用auth()方法进行验证。  
  834. Debug模式打开,可以看到详细的SMTP命令代码。也有助于我们排错。  
  835.   
  836.   
  837.   
  838. (27) MIME::Base64, encode_base64(), decode_base64()  
  839.   
  840. #!/usr/bin/perl -w  
  841.   
  842. use strict;  
  843. use MIME::Base64;  
  844.   
  845. foreach(<DATA>)  
  846. {  
  847. print decode_base64($_);  
  848. }  
  849. exit 0;  
  850.   
  851. __DATA__  
  852. xOO6w6Osu7bTrcC0tb1jaGluYXVuaXguY29tIFtwZXJsXbDmIQo=  
  853. 1eLKx2Jhc2U2NLHgwuu1xMD919OjrNPJTUlNRTo6QmFzZTY0xKO/6cC0veLC66GjCg==  
  854. cGVybGRvYyBNSU1FOjpCYXNlNjQgZm9yIGRldGFpbHMsIGVuam95IGl0IDopCg==  
  855.   
  856.   
  857. 用来处理MIME/BASE64编码。  
  858.   
  859.   
  860.   
  861. (28) Net::IMAP::Simple, login(), mailboxes(), select(), get()...  
  862.   
  863. #!/usr/bin/perl  
  864.   
  865. use strict;  
  866. use Net::IMAP::Simple;  
  867.   
  868. my $server = new Net::IMAP::Simple( 'imap.0451.com' );  
  869. $server->login( 'user_name', 'passwd');  
  870.   
  871. #show the mailboxs  
  872. #map {print "$_\n";} $server->mailboxes();  
  873.   
  874. #show mail's content  
  875. my $n = $server->select( 'inbox' ) or die "no this folder\n";  
  876. foreach my $msg ( 1..$n )  
  877. {  
  878. my $lines = $server->get( $msg );  
  879. print @$lines;  
  880. print "_________________ Press enter key to view another! ...... __________________\n";  
  881. read STDIN, my $key, 1;  
  882. }  
  883.   
  884. exit 0;  
  885.   
  886.   
  887. 在取得中文的Folder时,会出现乱码的情况,  
  888. 这个问题现在没有解决。英文的Folder则没问题。  
  889.   
  890. IMAP协议,默认端口为143,可以用telnet登录。  
  891.   
  892.   
  893.   
  894. QUOTE:telnet imap.xxx.com 143  
  895. 2 login user pass  
  896. 2 list "" *  
  897. 2 select inbox  
  898. ......  
  899.   
  900.   
  901. (29) Bio::DB::GenBank, Bio::SeqIO  
  902.   
  903. bioperl(http://bioperl.org/)模块使用--生物信息学中用的模块  
  904. 功能:根据核酸的gi号自动从GenBank中提取FASTA格式的序列,可以多序列提取。  
  905.   
  906.   
  907.   
  908. QUOTE:#!/usr/bin/perl -w  
  909.   
  910. use Bio::DB::GenBank;  
  911. use Bio::SeqIO;  
  912. my $gb = new Bio::DB::GenBank;  
  913.   
  914. my $seqout = new Bio::SeqIO(-fh => *STDOUT, -format => 'fasta');  
  915.   
  916. # if you want to get a bunch of sequences use the batch method  
  917. my $seqio = $gb->get_Stream_by_id([ qw(27501445 2981014)]);  
  918.   
  919. while( defined ($seq = $seqio->next_seq )) {  
  920. $seqout->write_seq($seq);  
  921. }  
  922.   
  923.   
  924. (30) Spreadsheet::ParseExcel  
  925.   
  926. perl解析Excel文件的例子。  
  927.   
  928.   
  929.   
  930. QUOTE:#!/usr/bin/perl -w  
  931.   
  932. use strict;  
  933. use Spreadsheet::ParseExcel;  
  934. use Spreadsheet::ParseExcel::FmtUnicode; #gb support  
  935.   
  936. my $oExcel = new Spreadsheet::ParseExcel;  
  937.   
  938. die "You must provide a filename to $0 to be parsed as an Excel file" unless @ARGV;  
  939. my $code = $ARGV[1] || "CP936"; #gb support  
  940. my $oFmtJ = Spreadsheet::ParseExcel::FmtUnicode->new(Unicode_Map => $code); #gb support  
  941. my $oBook = $oExcel->Parse($ARGV[0], $oFmtJ);  
  942. my($iR, $iC, $oWkS, $oWkC);  
  943. print "FILE :", $oBook->{File} , "\n";  
  944. print "COUNT :", $oBook->{SheetCount} , "\n";  
  945.   
  946. print "AUTHOR:", $oBook->{Author} , "\n"  
  947. if defined $oBook->{Author};  
  948.   
  949. for(my $iSheet=0; $iSheet < $oBook->{SheetCount} ; $iSheet++)  
  950. {  
  951. $oWkS = $oBook->{Worksheet}[$iSheet];  
  952. print "--------- SHEET:", $oWkS->{Name}, "\n";  
  953. for(my $iR = $oWkS->{MinRow} ;  
  954. defined $oWkS->{MaxRow} && $iR <= $oWkS->{MaxRow} ;  
  955. $iR++)  
  956. {  
  957. for(my $iC = $oWkS->{MinCol} ;  
  958. defined $oWkS->{MaxCol} && $iC <= $oWkS->{MaxCol} ;  
  959. $iC++)  
  960. {  
  961. $oWkC = $oWkS->{Cells}[$iR][$iC];  
  962. print "( $iR , $iC ) =>", $oWkC->Value, "\n" if($oWkC);  
  963. }  
  964. }  
  965. }  
  966.   
  967.   
  968. (31) Text::CSV_XS, parse(), fields(), error_input()  
  969.   
  970. 如果field里面也包含分隔符(比如"tom,jack,jeff","rose mike",O'neil,"kurt,korn"),那么我们  
  971. 解析起来确实有点麻烦,  
  972. Text::CSV_XS挺方便。  
  973.   
  974.   
  975.   
  976. QUOTE:#!/usr/bin/perl  
  977.   
  978. use strict;  
  979. use Text::CSV_XS;  
  980.   
  981. my @columns;  
  982. my $csv = Text::CSV_XS->new({  
  983. 'binary' => 1,  
  984. 'quote_char' => '"',  
  985. 'sep_char' => ','  
  986. });  
  987.   
  988. foreach my $line(<DATA>)  
  989. {  
  990. chomp $line;  
  991. if($csv->parse($line))  
  992. {  
  993. @columns = $csv->fields();  
  994. }  
  995. else  
  996. {  
  997. print "[error line : ", $csv->error_input, "]\n";  
  998. }  
  999.   
  1000. map {printf("%-14s\t", $_)} @columns;  
  1001. print "\n";  
  1002. }  
  1003. exit 0;  
  1004.   
  1005. __DATA__  
  1006. id,compact_sn,name,type,count,price  
  1007. 37,"ITO-2003-011","台式机,compaq","128M","290","1,2900"  
  1008. 35,I-BJ-2003-010,"显示器,硬盘,内存",'三星',480,"1,4800"  
  1009. 55,"C2003-104",笔记本,"Dell,Latitude,X200",13900,"1,13900"  
  1010.   
  1011.   
  1012. (32) Benchmark  
  1013.   
  1014. #!/usr/bin/perl  
  1015.   
  1016. use Benchmark;  
  1017.   
  1018. timethese(100,  
  1019. {  
  1020. 'local'=>q  
  1021. {  
  1022. for(1..10000)  
  1023. {  
  1024. local $a=$_;  
  1025. $a *= 2;  
  1026. }  
  1027. },  
  1028.   
  1029. 'my'=>q  
  1030. {  
  1031. for(1..10000)  
  1032. {  
  1033. my $a=$_;  
  1034. $a *= 2;  
  1035. }  
  1036. }  
  1037. });  
  1038.   
  1039.   
  1040. 可以拿来计算algorithm耗费多少时间.  
  1041.   
  1042.   
  1043. QUOTE:timethese(做几次iteration,{  
  1044. 'Algorithm名稱'=>q{ 要计算时间的algorithm },  
  1045. 'Algorithm名稱'=>q{ 要计算时间的algorithm }  
  1046. });  
  1047.   
  1048.   
  1049.   
  1050. (33) HTTP:: Daemon, accept(), get_request()...  
  1051.   
  1052. 一个简单的,只能处理单一请求的Web服务器模型。  
  1053. send_file_response()方法能把Client请求的文件传送过去。  
  1054.   
  1055.   
  1056. QUOTE:#!/usr/bin/perl  
  1057.   
  1058. use HTTP:: Daemon;  
  1059.   
  1060. $| = 1;  
  1061. my $wwwroot = "/home/doc/";  
  1062. my $d = HTTP:: Daemon->new || die;  
  1063. print "Perl Web-Server is running at: ", $d->url, " ...\n";  
  1064.   
  1065. while (my $c = $d->accept)  
  1066. {  
  1067. print $c "Welcome to Perl Web-Server<br>";  
  1068.   
  1069. if(my $r = $c->get_request)  
  1070. {  
  1071. print "Received : ", $r->url->path, "\n";  
  1072. $c->send_file_response($wwwroot.$r->url->path);  
  1073. }  
  1074.   
  1075. $c->close;  
  1076. }  
  1077.   
  1078.   
  1079. (34) Array::Compare, compare(), full_compare()...  
  1080.   
  1081. 用于数组比较。  
  1082. 本例实现类似shell command - diff的功能。  
  1083. 如果我们要比较的不是文件,而是比如系统信息,远程文件列表,数据库内容变化等,这个模块会给我们提供方便灵活的操作。  
  1084.   
  1085.   
  1086. QUOTE:#!/usr/bin/perl  
  1087.   
  1088. use Array::Compare;  
  1089.   
  1090. $comp = Array::Compare->new(WhiteSpace => 1);  
  1091. $cmd = "top -n1 | head -4";  
  1092. @a1 = `$cmd`;  
  1093. @a2 = `$cmd`;  
  1094.   
  1095. @result = $comp->full_compare(@a1, @a2);  
  1096.   
  1097. foreach(@result)  
  1098. {  
  1099. print $_ + 1, "th line:\n";  
  1100. print "> $a1[$_]> $a2[$_]";  
  1101. print "-----\n";  
  1102. }  
  1103. exit 0;  
  1104.   
  1105.   
  1106. (35) Algorithm::Diff, diff()  
  1107.   
  1108. 用于文件比较。  
  1109. 实现类似unix command diff的功能。  
  1110.   
  1111. #!/usr/bin/perl  
  1112.   
  1113. use Algorithm::Diff qw(diff);  
  1114.   
  1115. die("Usage: $0 file1 file2\n") if @ARGV != 2;  
  1116.   
  1117. my ($file1, $file2) = @ARGV;  
  1118. -T $file1 or die("$file1: binary\n");  
  1119. -T $file2 or die("$file2: binary\n");  
  1120.   
  1121. @f1 = `cat $file1 `;  
  1122. @f2 = `cat $file2 `;  
  1123.   
  1124. $diffs = diff(@f1, @f2);  
  1125.   
  1126. foreach $chunk (@$diffs)  
  1127. {  
  1128. foreach $line (@$chunk)  
  1129. {  
  1130. my ($sign, $lineno, $text) = @$line;  
  1131. printf "$sign%d %s", $lineno+1, $text;  
  1132. }  
  1133.   
  1134. print "--------\n";  
  1135. }  
  1136.   
  1137.   
  1138. (36) List::Util, max(), min(), sum(), maxstr(), minstr()...  
  1139.   
  1140. 列表实用工具集。  
  1141.   
  1142.   
  1143. QUOTE:#!/usr/bin/perl  
  1144.   
  1145. use List::Util qw/max min sum maxstr minstr shuffle/;  
  1146.   
  1147. @s = ('hello', 'ok', 'china', 'unix');  
  1148.   
  1149. print max 1..10; #10  
  1150. print min 1..10; #1  
  1151. print sum 1..10; #55  
  1152. print maxstr @s; #unix  
  1153. print minstr @s; #china  
  1154. print shuffle 1..10; #radom order  
  1155.   
  1156.   
  1157. (37) HTML::Parser  
  1158.   
  1159. 解析HTML。本例为找出一个html文本中的所有图片的地址。(即IMG标签中的src)  
  1160.   
  1161. 子程序start中的"$tag =~ /^img$/"为过滤出img标签。  
  1162. 如果换为"$tag =~ /^a$/",即是找出所有的链接地址。  
  1163.   
  1164. 详细的方法介绍,请见`perldoc HTML::Parser`  
  1165.   
  1166.   
  1167.   
  1168. QUOTE:#!/usr/bin/perl  
  1169.   
  1170. use LWP::Simple;  
  1171. use HTML::Parser;  
  1172.   
  1173. my $url = shift || "http://www.chinaunix.net";  
  1174. my $content = LWP::Simple::get($url) or die("unknown url\n");  
  1175.   
  1176. my $parser = HTML::Parser->new(  
  1177. start_h => [&start, "tagname, attr"],  
  1178. );  
  1179.   
  1180. $parser->parse($content);  
  1181. exit 0;  
  1182.   
  1183. sub start  
  1184. {  
  1185. my ($tag, $attr, $dtext, $origtext) = @_;  
  1186. if($tag =~ /^img$/)  
  1187. {  
  1188. if (defined $attr->{'src'} )  
  1189. {  
  1190. print "$attr->{'src'}\n";  
  1191. }  
  1192. }  
  1193. }  
  1194.   
  1195.   
  1196. (38) Mail::Sender  
  1197.   
  1198. 1)发送附件  
  1199.   
  1200.   
  1201.   
  1202. QUOTE:#!/usr/bin/perl  
  1203.   
  1204. use Mail::Sender;  
  1205.   
  1206. $sender = new Mail::Sender{  
  1207. smtp => 'localhost',  
  1208. from => 'xxx@localhost'  
  1209. };  
  1210. $sender->MailFile({  
  1211. to => 'xxx@xxx.com',  
  1212. subject => 'hello',  
  1213. file => 'Attach.txt'  
  1214. });  
  1215. $sender->Close();  
  1216.   
  1217. print $Mail::Sender::Error eq "" ? "send ok!\n" : $Mail::Sender::Error;  
  1218.   
  1219.   
  1220. 2)发送html内容  
  1221.   
  1222.   
  1223.   
  1224. QUOTE:#!/usr/bin/perl  
  1225.   
  1226. use Mail::Sender;  
  1227.   
  1228. open(IN, "< ./index.html") or die("");  
  1229.   
  1230. $sender = new Mail::Sender{  
  1231. smtp => 'localhost',  
  1232. from => 'xxx@localhost'  
  1233. };  
  1234.   
  1235. $sender->Open({  
  1236. to => 'xxx@xxx.com',  
  1237. subject => 'xxx',  
  1238. msg => "hello!",  
  1239. ctype => "text/html",  
  1240. encoding => "7bit",  
  1241. });  
  1242.   
  1243. while(<IN>)  
  1244. {  
  1245. $sender->SendEx($_);  
  1246. }  
  1247. close IN;  
  1248. $sender->Close();  
  1249.   
  1250. print $Mail::Sender::Error eq "" ? "send ok!\n" : $Mail::Sender::Error;  
  1251.   
  1252. 发送带有图片或其他信息的html邮件,请看`perldoc Mail::Sender`  
  1253. 中的"Sending HTML messages with inline images"及相关部分。  
  1254.   
  1255.   
  1256.   
  1257. (39) Time::HiRes, gettimeofday(), usleep()  
  1258. (40) Image::Magick  
  1259.   
  1260.   
  1261. http://www.imagemagick.org/www/perl.html  
  1262.   
  1263.   
  1264.   
  1265. QUOTE:#!/usr/local/bin/perl  
  1266. use Image::Magick;  
  1267.   
  1268. my($image, $x);  
  1269.   
  1270. $image = Image::Magick->new;  
  1271. $x = $image->Read('girl.png', 'logo.png', 'rose.png');  
  1272. warn "$x" if "$x";  
  1273.   
  1274. $x = $image->Crop(geometry=>'100x100"+100"+100');  
  1275. warn "$x" if "$x";  
  1276.   
  1277. $x = $image->Write('x.png');  
  1278. warn "$x" if "$x";  
  1279.   
  1280.   
  1281. The script reads three images, crops them, and writes a single image as a GIF animation  
  1282. sequence. In many cases you may want to access individual images of a sequence. The next  
  1283. example illustrates how this is done:  
  1284.   
  1285.   
  1286.   
  1287. QUOTE:#!/usr/local/bin/perl  
  1288. use Image::Magick;  
  1289.   
  1290. my($image, $p, $q);  
  1291.   
  1292. $image = new Image::Magick;  
  1293. $image->Read('x1.png');  
  1294. $image->Read('j*.jpg');  
  1295. $image->Read('k.miff[1, 5, 3]');  
  1296. $image->Contrast();  
  1297. for ($x = 0; $image->[x]; $x++)  
  1298. {  
  1299. $image->[x]->Frame('100x200') if $image->[x]->Get('magick') eq 'GIF';  
  1300. undef $image->[x] if $image->[x]->Get('columns') < 100;  
  1301. }  
  1302. $p = $image->[1];  
  1303. $p->Draw(stroke=>'red', primitive=>'rectangle', points=>20,20 100,100');  
  1304. $q = $p->Montage();  
  1305. undef $image;  
  1306. $q->Write('x.miff');  
  1307.   
  1308.   
  1309. Suppose you want to start out with a 100 by 100 pixel white canvas with a red pixel in the  
  1310. center. Try  
  1311.   
  1312.   
  1313.   
  1314. QUOTE:$image = Image::Magick->new;  
  1315. $image->Set(size=>'100x100');  
  1316. $image->ReadImage('xc:white');  
  1317. $image->Set('pixel[49,49]'=>'red');  
  1318.   
  1319.   
  1320. Or suppose you want to convert your color image to grayscale:  
  1321.   
  1322.   
  1323.   
  1324. QUOTE:$image->Quantize(colorspace=>'gray');  
  1325.   
  1326. Here we annotate an image with a Taipai TrueType font:  
  1327.   
  1328. $text = 'Works like magick!';  
  1329. $image->Annotate(font=>'kai.ttf', pointsize=>40, fill=>'green', text=>$text);  
  1330.   
  1331.   
  1332. Other clever things you can do with a PerlMagick objects include  
  1333.   
  1334.   
  1335.   
  1336. QUOTE:$i = $#$p"+1"; # return the number of images associated with object p  
  1337. push(@$q, @$p); # push the images from object p onto object q  
  1338. @$p = (); # delete the images but not the object p  
  1339. $p->Convolve([1, 2, 1, 2, 4, 2, 1, 2, 1]); # 3x3 Gaussian kernel  
  1340.   
  1341.   
  1342. (41) Data::SearchReplace  
  1343.   
  1344.   
  1345. #!/user/bin/perl  
  1346. use Data::SearchReplace ('sr');  
  1347. sr({ SEARCH => 'searching', REPLACE => 'replacing'}, \$complex_var);  
  1348.   
  1349. # or OO  
  1350.   
  1351. use Data::SearchReplace;  
  1352. $sr = Data::SearchReplace->new({ SEARCH => 'search for this',  
  1353. REPLACE => 'replace with this' });  
  1354.   
  1355. $sr->sr(\$complex_var);  
  1356. $sr->sr(\$new_complex_var);  
  1357.   
  1358. # if you want more control over your search/replace pattern you  
  1359. # can pass an entire regex instead complete with attributes  
  1360.   
  1361. sr({ REGEX => 's/nice/great/gi' }, \$complex_var);  
  1362.   
  1363. # you can even use a subroutine if you'd like  
  1364. # the input variable is the value and the return sets the new  
  1365. # value.  
  1366.   
  1367. sr({ CODE => sub { uc($_[0]) } }, \$complex_var);  
  1368.   
  1369.   
  1370.   
  1371. QUOTE:use Data::SearchReplace qw(sr);  
  1372. sr({SEARCH => 'find', REPLACE => 'replace'}, \@data);  
  1373. sr({REGEX => 's/find/replace/g'}, \%data);  
  1374. sr({CODE => sub {uc($_[0])} }, \@data);   
0 0
原创粉丝点击