Perl - TMTOWTDI 宋政隆 Perl User. Outline What is Perl? Why learn/use Perl? How to get Perl?...

Post on 26-Dec-2015

254 views 2 download

Transcript of Perl - TMTOWTDI 宋政隆 Perl User. Outline What is Perl? Why learn/use Perl? How to get Perl?...

Perl - TMTOWTDI宋政隆

Perl User

Outline What is Perl? Why learn/use Perl? How to get Perl? Things about Perl…

What is Perl?

Practical Extraction and Report Language

Wrong Answer!!

Pathologically Eclectic Rubbish Lister

See http://perldoc.perl.org/perl.html#BUGS

Just name it

Perl

病態地 不拘一格的

廢物製表者

福利汽車 不賣調表車、法拍車、權利車、流當車、 AB車、改裝車,我們給消費者的保證: 車是給您買回去開的,不是給您買回去修理的。

Perl 方便、好用、穩定、功能強大、移植性高,我們給使用者的保證: There's more than one way to do it (TMTOWTDI)

對 Perl 的印象

對 Perl 的印象 Picture from DanCentury

Google ‘perl’ suggestion

Perl code 很難懂 ?

為什麼要會

Perl?

Why should I learn/use Perl? Perl is fun Perl is useful for…

Text processing Web programming System administration Game programming Scientific research

bio-informatics, linguistics

Open Source

How to ‘get’ perl?

工欲善其事必先利其器

50% 以上的人 , 因為沒有好用的 GUI 編輯器而不用 Perl

60% 以上的人 , 因為覺得 Perl 很難而不想用…

How to ‘get’ Perl – Windows Strawberry Perl

For Windows only Just the same as Perl elsewhere http://strawberryperl.com/ Recommended!!

ActivePerl For Windows, Linux, Mac OS X, Solaris, AIX and HP-UX

http://www.activestate.com/activeperl/

Padre – a Perl IDE

Perl briefsData types

Control flowRegular expressions

Data Types Scalars Arrays Hashes References File Handles Objects

Scalars Numbers

Decimal floating point (Can be made integer, octal, hexadecimal)

Strings Can contain any character Can be null: “” Can be undef

Scalars Perl $int = 1; $float = 0.2; $negative = -3; $string = “hello”;

C/C++ int i = 1; float j = 0.2; int k = -3; char* str = “hey”;

Strings Single-quoted

characters are as shown with only two exceptions. single-quote in a single-quoted string requires \’ backslash in a single-quoted string requires \\

Double-quoted it will interpolate – calculate variables or control sequences.

For example $foo = “myfile”; $datafile = “$foo.txt”; will result in the variable $datafile holding the string “myfile.txt”

Another example print ‘Howdy\n’; will print:

Howdy\n print “Howdy\n”; will print

Howdy

(\n is a control sequence, standing for “new line”).

Scalar operators Math, just like C/C++

*, /, %, **, etc. Strings

x to repeat the thing on the left “hi” x 5 gives “hihihihihi”

. concatenates strings “Hello” . “ World!”

Perl knows to convert when mixing these two types: “3”*7 gives 21 “3”.7 gives “37”

Comparing ScalarsComparison Numeric String

Equal == eq Not equal != ne Less than < lt Greater than > gt Less or equal <= le Greater or equal >= ge

8 < 25 TRUE!“8” lt “25” FALSE!

Variables A sign, followed by a letter, followed by pretty m

uch whatever. Sign determines the type:

$foo is a scalar @foo is a array hold a list of scalars %foo is a hash

Variables default to global (they apply in all parts of your program). This can be problematic. local $var will make the variable active only for the cu

rrent “block” of code. my $var does the same, and dies when out the current “b

lock”

Using Arrays Elements are indexed, from 0.

my @animals = (“frog”, “bear”, “elephant”); $animals[2]; # elephant Note: element is a scalar, so $ rather than @

Subsections are “slices”. my @mammals = @animals[1,2];

Lots of functions for push, pop … splitting a scalar string into an array

my $sentence = “元智大學 資訊工程系” ; my @words = split(“ “, $sentence);# @words contains (“元智大學” , “資訊工程系” );

Control flow Control structures (generally like C/C++)

if / then / elsif / else while do {} while do {} until for () / foreach() # loops over a list switch (NOTE: After perl 5.10) …

Errors / warnings die “message” terminates program and output “message

”. warn “message” give you a warning and keeps going.

Hashes “Associative arrays” A set of

values (any scalar), indexed by keys (strings)

Example my %info; $info{ “name” } = “ ”宋政隆 ; $info{ “age” } = 32; $info{ “future” } = undef;

hashes 與 arrays 可以摻在一起用 arrays of arrays, arrays of hashes, hashes of arrays …

Matching string patterns using regular expressions m/pattern/ will check the last stored variable ($_) for p

attern. $var =~ m/pattern/; will check $var for pattern. If the pattern is in $var, then

$var =~ m/pattern/ is TRUE. If you “group” part of the pattern and it is present,

$var =~ m/(pattern)/ is true, AND, now a variable names $1 contains the first match it found.

Group more pieces of the pattern and the matches are stored in $2, $3, etc.

This only grabs the *first* match. To grab all, say my @matches = ($var =~ m/(pattern)/g); This will store every match in the array @matches.

Regular expression\([Ii]f \|and \)*\(<i>[AC]\+<\/i>.\)\(and\)\?

What’s a “regular expression”?

. any single character* zero or more of the previous+ one or more of the previous? zero or one of the previous{n} match exact n times{n,} match at least n times{n,m} match at least n but not more than m times[] character class^ beginning of the line$ end of the line\b word boundary\d \D digit / non-digit\s \S space / non-space\w \W word character / non-word character| or – match this or that() grouping

Examples 資工 |資訊工程 “資工” or “資訊工程” \d{2,3}-\d\d\d-\d\d\d\d 有區碼電話號碼 \d{4}-\d\d\d\d\d\d 手機號碼 (?\d{2,3}-)?\d\d\d-\d\d\d\d 區碼可有可無 \b[aeiou]\w+ 母音開頭的字 [[:alpha:]]+ 任意字母 \b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b Email [-+]?[0-9]*\.?[0-9]+ floating point

Try yourself!!! Rubular

Perl by examples

小事 ? 交給 Perl 就搞定了 !Get a webpage’s PageRank奇摩字典

Example: Google Page Rank

If you’re using a script...

Example: Google Page Rank http://pagerankalert.com/

Maybe I can just write a parser for this page…

Google Page Rank via LWP::UserAgentuse LWP::UserAgent; # Web User Agent Class

my $url = shift;my $ua = LWP::UserAgent->new();push @{ $ua->requests_redirectable }, 'POST';my $r = $ua->post ('http://pagerankalert.com/search', Content => [ 'pagina[address]' => $url,]);$r->decoded_content =~ m/pagerank (\d+) for .+/;print $1;

% perl pr.pl www.cse.yzu.edu.tw 6

There's More Than One Way To Do It.

What if I forgot to set $ua->requests_redirectable

?

Google Page Rank via WWW::Mechanizeuse WWW::Mechanize; # Handy web browsing in a Perl Object

my $url = shift;my $mech = WWW::Mechanize->new();$mech->get ('http://pagerankalert.com/search‘);$mech->submit_form ( fields => [ 'pagina[address]' => $url,]);$mech->content =~ m/pagerank (\d+) for .+/;print $1;

% perl mpr.pl www.cse.yzu.edu.tw 6

There's More Than One Way To Do It.

Hey! they’re too handy!Is there exist any

simpler way?

Comprehensive Perl Archive

NetworkCPAN

is Your best friend!!

Google Page Rank via WWW::Google::PageRank

use WWW::Google::PageRank;

my $url = shift;my $gpr = WWW::Google::PageRank->new();print scalar($gpr->get ($url));

% perl mpr.pl www.cse.yzu.edu.tw 6

What is CPAN Since 1995-10-26 Collection of Perl software/class/documentation

DRY (Don’t Repeat Yourself) 8000+ authors ~18000 modules Testers report for ALL module

哇 ~ CPAN 這麼好用

我現在就來用…可是…

國內 Perl 常見問題

哇 ~ CPAN 這麼好用

我要怎麼用呢 ?CPAN

CPANPLUScpanminus

CPAN% cpan <Module>

Sorry, we have to rerun the configuration dialog for CPAN.pm due to some missing parameters...

… 問問題 , 回答問題 … 再問一堆很煩的東西 … 要是失敗了 , 又要重來 … 苦手 動不動就問你問題 , 不答還不行

CPANPLUS 為了取代繁瑣指令的 CPAN, 結果… 要安裝 CPANPLUS, 要先安裝好多好多的 Modules ( 雞生蛋 蛋生雞 ?) 結果…

% cpanp <Module> CPANPLUS::Shell::Default -- CPAN exploration and module installation (v0.88) *** Please report bugs to <bug-cpanplus@rt.cpan.org>. *** Using CPANPLUS::Backend v0.88. ReadLine support enabled. … … 也問一堆很煩的東西 … 要是失敗了 , 會直接跳出 … 苦手

There's More Than One Way To Do It.怎麼連安裝程式也有

cpanminus http://search.cpan.org/dist/App-cpanminus/

安裝簡單% wget http://xrl.us/cpanm% chmod +x cpanm

沒有 root 權限 , 就幫你安裝在自家目錄% cpanm <Module>…done… no questions

cpanminus screen screenshot

There's More Than One Way To Do It.What if there’s

NO Useful Module?

奇摩字典文字介面 – 舊版 From jiing’s flickr

奇摩字典

Original Source code

奇摩字典 http://tw.dictionary.yahoo.com/

奇摩字典 http://tw.dictionary.yahoo.com/

New ydict.pl!

There's More Than One Way To Do It.

Do I really need to use regex to parse the result? What if the layout changed?

奇摩字典 - TMTOWTDI

YAML – YAML Ain't Markup Language# http://tw.dictionary.yahoo.comauthor: Cheng-Lung Sunghandle: http://tw\.dictionary\.yahoo\.comxtitle: //div[@class="summary"]//h3defs: //div[@class="def clr nobr"]errormsg: //p[@class="ico"]caption: .//div[@class="caption"]explain: .//p[@class="interpret"]example: ../..//p[@class="example"]

use WWW::Scramble

如果又改版了我們也不用再動到程式

只要將YAML 檔

重新編寫即可

Perl jobs?Indeed.com104.com

我學 Perl 有用嗎 ?

Indeed.com

Indeed.com

Indeed.com

學 Perl 有 $途 嗎 ?

學 Perl 有 $途 嗎 ?

學 Perl 有 $途 嗎 ?

學 Perl 有 $途 嗎 ?

學 Perl 有 $途 嗎 ? – 104.com 擅長工具 : 工作需求量 Perl : 63 Python : 39 Ruby : 9 PHP : 173 C++ : 641 Java : 541

有什麼跟 Perl 有關 但還沒講到的 ? Perl 5.10

Named captured regular expression? Perl 5.12

… Yada Yada operator Object-Oriented Programming

Moose Event-driven Programming

POE AnyEvent

Web Catalyst Jifty Plack

Perl books - Philippe Lin

Perl resources Web

http://perl.org/ http://use.perl.org/ http://perldoc.perl.org/ Perl Monks Perl Mongers

http://taipei.pm.org http://chupei.pm.org

CPAN IRC

Freenode: #perl.tw, #elixus, #chupei.pm irc.perl.org: #perl, #news, #perl-help

Q & A謝謝大家

Pictures, Comics from The truth about Perl Juan Paredes – Blog Script to see if Perl is working ! :E ! NO PERL xkcd.com PHP-Nuke: Management and Programming