Post on 05-Jan-2016
What is Perl?
• PERL--Practical Extraction and Report Language
• Created as a way to process large text or files. – Create a script that opens one or more
files– Processes the information– Writes out results
What can it do?
• Perl can be used quite flexibly to “do something” with user input– append to a flat file– add it to a database– insert it into an email message– add it to an existing webpage– create a new webpage– display it in the browser’s window
Informations in Perl
• Online documentation on Perl– http://www.perl.com/– http://reference.perl.com/ follow a
tutorial hyperlink
• Books on Perl– Learning Perl from O’Reilly &
Associates– Series on Perl from O’Reilly &
Associates
Perl Examples I
• Create a first Perl program, “first.pl”– #!/usr/local/bin/perl– print “Hello, World\n”;
• chmod 755 first.pl • ./first.pl
Perl Example II
• Variables and Input Commands– #!/usr/local/bin/perl– $name="HAL";– print "Hello there. What is your name?\n";– $you = <STDIN>;– chop($you);– print "Hello, $you. My name is $name. Welcome to the CGI
Class.\n";
• There is no type in $variable_name
Perl Example III
• Perl CGI program has to handle HTML !!– #!/usr/local/bin/perl– print "Content-type:text/html\n\n";– print "<html><head><title>Test
Page</title></head>";– print "<body>";– print "<h2>Hello, world!</h2>";– print "</body></html>";
• This handles HTML output only, how about input? --> needs HTML FORM
Perl 제어문
• if ( 조건식 ) { …} • if ( 조건식 ) { …} else {…}• if ( 조건식 1) { … } elsif ( 조건식 2)
{…} else {…}• while ( 조건식 ) { …. }• do { … } while ( 조건식 );• for ($i=0;$i<=10;$i++) { …}• foreach $ 변수 리스트 { …}
Perl File Handling
• FileHandle : Name for I/O connection• STDIN, STDOUT, STDERR are given• Other Files
– Open(FILEHANDLE, “somename”);– FILEHANDLE is a name being used in
Perl– “somename” is a file name in OS– Open(OUT, “>outfile”);– Open(LOGFILE, “>>mylogfile”);– Close(LOGFILE);
Input/Output to File
open (FIL , “some-file”);
while ( $_ = <FIL> ) {
chop;
print STDOUT “some-file has $_ !\n”;
}
close(FIL);
Flat File Database
• A text file database• Each line of the file is a new record in DB• The fields are separated by pipe symbol(|)• guestbook.dat
Sunghun Park|sunghun.park@mail.utexas.edu|Testing
Joe Smith|jsmith@mail.utexas.edu|Hello Everybody
guestbrowse.cgi
#!/usr/local/bin/perlrequire 'cgi-lib.pl'; # Include library + use itprint "Content-type: text/html\n\n";print "<HTML><h1>The Contents of Guestbook</h1>";print "<TABLE BORDER=1>\n";print "<TR><TD>Name of Guest</TD><TD>E-Mail</TD><TD>Comments from Guest</TD>\n";open(GUESTBOOK,"guestbook.dat") || die "\n<H1>Can't Open Guestbook file!</H1>";while (<GUESTBOOK>) { chop($_); ($name, $email, $comment) = split(/\|/, $_); print "<TR><TD> $name </TD><TD> <A HREF=\"mailto:$email\">$email </A></TD><TD>$comment </TD></TR>\n";}print "</TABLE>\n";close(GUESTBOOK);
Split Function
• Split takes a regular expression and a string
• Split returns a list of values• $line = “C:\\;;C:\\Windows\\;”;• @fields = split(/;/, $line);• now $fields is (“C:\”, “”, “C:\Windows”)• @fields 는 첨자형 변수 전체를 지칭• $fields[0], $fields[1], $fields[2] 는 각각의
첨자형변수
Perl 첨자형 변수 (2 가지 )• 단순한 변수는 $x, $y• $days[28] 는 첨자형 변수
– $#days 는 @days 의 마지막 첨자 값을 표시함– $days[0], $days[1], $days[2], ….$days[$#days]
• $days{‘Feb’} 는 associate array 를 표시– 전체는 %days 로 표시한다– ( 키값 1, 값 1, 키값 2, 값 2, ….)– $days{‘Jan’} 등으로 사용한다– VB 의 ReQuest.QueryString(“name”) 등의 기능은
여기서 왔다– foreach $i (keys %ENV) print “$i = $ENV{$i}”;
Searching in Perl I
• Powerful pattern matching with regular expression to a string
• More general than wild card file or dir name• while (<>) {
– if ( /ab*c/ ) {• print $_;
– } }• substitue operator
– s/abc*c/def/;
Searching in Perl II
• If pattern to search is not in $_, use =~
• $a = “hello world”;• $a =~ /^he/;• $a =~ /$b/i
Regular Expression 1
• Powerful pattern matching with regular expression to a string
• while (<>) {– if ( /ab*c/ ) {
• print $_;
– } }
• substitute operator– s/abc*c/def/;
• /pattern/
Regular Expression 2
• Regular Expression 은 Pattern 을 설명한다
• 문자 하나짜리 Pattern– /./ : . 는 \ n 을 제외한 어떤 문자와도 매칭이됨– / a./ : a 로 시작하고 두개 문자로 된 문자열– /[abcde]/ : 다섯개 문자중 어느거나 – /[aeiouAEIOU]/ : 모든 영문자 모음과 매칭– /[0123456789]/ 혹은 /[0-9]/– /[^0-9]/ : 숫자가 아닌 어떤 문자와 매칭
Regular Expression 3
• 간편하게 표시하는 문자 하나 짜리 패턴– \ d (a digit): [0-9]– \D : [^0-9]– \w (word char): [a-zA-Z0-9_]– \W : [^a-zA-Z0-9_]– \s (space): [ \r\t\n\f]– \S : [^ \r\t\n\f]
Regular Expression 4
• Grouping Pattern( 패턴 그룹 )– Sequence : 순서대로 나열
• Abc
– Multiplier : 바로 앞 패턴의 반복• * : 0 번 이상 반복 (0 번도 O.K.)• + : 1 번 이상 반복• ? : 0 혹은 1 번• 예 ) /fo+ba?r/ 는 어떤 문자열과 매칭이 될까 ?• / x{5,10}/ : 최소 5 개의 x 에서 10 개의 x 와
매칭
Regular Expression 5
• Grouping Pattern( 패턴 그룹 )– 괄호를 이용한 기억
• / a(.*)b\1c/ : \1 은 첫번째 괄호에 해당되는 패턴– aFREDbFREDc 혹은 abc 는 ?, aXXbXXXc 는 ?
• s/a(.*)b(.*)c/$1B$2/
– Alternation( 선택 )• / a|b|c/ 혹은 / song|blue/
Regular Expression 6
• Anchoring Pattern( 패턴 고정하기 )– \ b : 단어의 시작을 지정
• / fred\b/ : fred 는 성공 frederick 은 실패• /\bmo/ : mo 와 moe 는 성공 Elmo 는 실패
– /^a/ : 문자열의 첫글자가 a 에 매칭하면 성공• / a^/ : 는 ^ 의 특수한 의미를 상실함… .
– /a$/ : 문자열의 마지막 글자가 a 에 매칭하면 성공• 패턴 중간에 $ 문자를 사용하려면 \$ 를 쓰도록
Regular Expression 7
• Precedence( 우선 순위 )– 만약 a|b* 라는 패턴은 ?– Regular Expression Operator 의 우선순위
• 1 등 : 괄호 ( )• 2 등 : 반복 (*) ? + * {m,n}• 3 등 : sequence 와 anchoring : abc ^ $• 마지막 : 선택 ( | )
– abc*, (abc)*, ^x|y, ^(x|y), a|bc|d
Target($_) 을 바꾸는 방법
• If pattern to search is not in $_, use =~
• $a = “hello world”;• $a =~ /^he/;• $a =~ /$b/i
– i 는 소문자 대문자 구별을 무시하도록 함
Delimiter 를 바꾸는 방법
• if ( <> =~ /\wwwroot\/docs/) { …}– /…/ 과 delimiter 로 사용되기 때문에
패턴내의 / 문자는 \ 를 동반해야 한다 !!!• 다른 문자를 delimiter 로 이용할 수 있다
– m@/wwwroot/docs/@– m#/wwwroot/doc/#
패턴에서 변수 사용
$what = “bird”;$sentence = “Every good bird does
fly.”;if ( $sentence =~ /\b$what\b/ ) {
print “The sentence has the word $what!\n”;}
문자열 변경• s/old-regex/new-string/• 예 1)
– $_ =“foot fool buffoon”;– s/foo/bar/g; # $_ 가 “ bart barl bufbarn” 로 변경
• 예 2)– $old = “hello world”;– $change = “goodbye”;– $old =~ s/hello/$change/;
• 예 3)– $_ =“this is a test”;– s/ (\w+)/<$1>/g; # $_ 는 “ <this> <is> <a>
<test>” 로 바꿤