Perl 정리 요약

2015.06.19 17:02

졸리운_곰 조회 수:507

Perl 정리 요약

출처:
http://blog.empas.com/wjsdhtn/26820847

 

목 차

머릿말

제1장 Perl 언어의 개요

1. 개요
2. Perl의 특징

제2장 Perl 언어의 문법

1. 간단한 예제(Hello world!)
2. 기본형
3. 변수
4. 배열
5. 입출력문
6. 제어문, 조건문
7. 정규표현식
8. 문자의 대용과 변환
9. 기본함수
10. 결합배열
11. 서브루틴

제3장 Perl 프로그래밍 활용

1. 사용자 정보
2. 계산기
3. 디스크사용량 정보
4. 전화번호 검색
5. 성적평가





1 Perl 언어의 개요

1. 개요

▣ Practical Extraction and Report Language
-Larry Wall (lwall@netlabs.com)가 고안해낸, 파일로 부터 데이타의 추출과 변환을 쉽게 구현할수있는
C, awk, sed, sh의 장점들을 취한 프로그래밍언어이다.

- UNIX, Mac, Amiga, OS/2, VMS, MS-DOS, Windows95등의 다양한 운영체제에서 사용가능하며 현재
버전5까지 배포되어있다.


2. Perl의 특징

▣ 인터프리터
- 실용적 (편이성, 능률성, 완벽한구조)이며, 실행되기위한 데이타의 크기에 제한이 없다.
패턴매칭테크닉이 탁월하며, 다른 언어의 스크립트와 바이너리를 모두취급할수있다.
- 97년 4월현재PERL 컴파일러가 aplha3버전까지 배포되었으며, 향후 인터프리터형식과 함께
존재할것이다.

▣ C + sed + awk + sh = "Perl"
- 아래의 각 언어의 장점들을 포함한것이 PERL 이다.
C (제어, 수치, I/O, 시스템호출)
sed (대용, 변환)
awk (삽입, 계산, 리스트, 처리)
sh (문자열, 결합, 사이클시간)

▣ Perl vs C 언어
- 거의 동일한 문법구조이며, 일반적으로 동일한 C 프로그램보다 느리다.





2 Perl 언어의 문법

1. 간단한 예제( Hello world! )

▣ 프로그램
- 다음을 vi, emacs, pico등의 에디터로 작성한다.

 

#!/usr/local/bin/perl
# Perl example<1> - hello world : hello.pl
#---------------------------

print 'Hello world!\n'; #statement line

#end of file

 

 



▣ 해설
- #!/usr/local/bin/perl
: Perl프로그램의 경로(Full Path)지정
: 스크립트(Script)가 수행될때 쉘(Shell)이 아닌 지정된 Perl프로그램에 의해 수행된다.

- # Perl example<1> - hello world : hello.pl
#---------------------------
#statement line
#end of file
: 주석(comment), 수행되지않는 부분
: '#' 심볼로 시작되는 해당라인은 수행시 무시

- print 'Hello world!\n';
: 수행되는 문장
: '\n'은 개행(newline)의 특수문자
: 라인의 끝은 세미콜론(;)으로 끝난다.

▣ 프로그램 실행
- 해당파일(exam.pl)의 허가권을 조정한다.
: %chmod u+x hello.pl

- 실행
: %perl hello.pl 또는 %hello.pl


2. 기본형

▣ 수치
- 정수형 : 0, 3, -100, -8
- 실수형 : 1.0, 7.653, -6.30, 10e23
- 8진수 : 0765, 0123 (0으로 시작)
- 16진수 : 0x268, 0x111 (0x로 시작)

▣ 문자와 문자열
- Single quote
'Hello' : 5 문자 h, e, l, l, o
- Double qoute
"Hello World!\n" : 문자열 Hello World!와 개행

▣ 연산자
- 산술연산자 : C 언어와 동일
- 비교연산자
내용 수치비교 스트링비교
Equal == eq
Not equal != ne
Less Than < lt
Greater Than > gt
Less Than or Equal to <- le
Greater Than or Equal to >- ge

- 연산자 우선순위
좌측결합 변수, 리스트연산자(좌측)
좌측결합 ->
- ++ --
우측결합 **
우측결합 ! ~ \ and unary + and -
좌측결합 =~ !~
좌측결합 * / % x
좌측결합 + - .
좌측결합 << >>
- named unary operators
- < > <= >= lt gt le ge
- == != <=> eq ne cmp
좌측결합 &
좌측결합 | ^
좌측결합 &&
좌측결합 ||
- ..
우측결합 ?:
우측결합 = += -= *= etc.
좌측결합 , =>
- 리스트 연산자 (우측)
좌측결합 not
좌측결합 and
좌측결합 or xor


3. 변수
▣ 스칼라 변수
- 변수선언이 없다.
- 형식 :
'$'로 시작되며 문자와 숫자, 밑줄문자(_)가 뒤에 올수있다.
- 대문자와 소문자의 구별 ($a != $A), case sensitive
▣ 산술연산
- 변수선언이 없다.
- C 언어의 산술연산식과 동일하다.
$a=1;
$b=$a+1;
$b++;
$c=$b;
$c+=$a;
- 예제

 

#!/usr/local/bin/perl
# scalar variable example (1)

$a = 34; # 정수형 상수 34를 $a에 치환
$b = 5; # $b를 $a에 치환
$sum = $a + $b; # $a와 $b를 더한값을 $sum에 치환
print "SUM = $a + $b = $sum\n";

$a = $a + 1; # $a에 1더한값을 $a에 치환
$b += 1; # $b에 1더한값을 $b에 치환
print "Increased A = $a , B = $b\n";

 

 



▣ 문자열
- 문자열의 선언없이 변수가 쓰인다.
$d="abcdefg";
$e="hijklmn";
- 예제

 

#!/usr/local/bin/perl
# scalar variable example (2)
$a_string = "Don\'t worry"; # Don't worry를 $a_string에 치환
$b_string = "Be happy!"; # Be happy를 $b_string에 치환

print "RESULT : $a_string and $b_string\n";
# print문의 수행 결과-> Don't worry and Be happy!

 

 



▣ 기타
- 숫자와 문자의 추가(append)연산
'.' : 추가
'x' : 반복 (형식 : $L_string = $R_string x $number )

$f=$d.$e;
$d.=$e;
- 예제 (1)

 

#!/usr/local/bin/perl
# scalar variable example (3)
#-------- Numeric
$a = 12;
$b = 0;
$a .= $b; # $a에 $b의 내용을 추가, $a = 120
print "APPEND B onto A = $a\n";

#-------- String
$a_string = 'Hong';
$b_string = ' Gil-Dong';
$c_string = $a_string . $b_string;
# $a_string와 $b_string를 연결하여 $c_string에 치환
# 즉, Hong Gil-Dong
print "CONCATENATE String: $c_string\n";

$repeat = 3;
$d_string = $a_string x $repeat;
# $a_string을 3번 반복하여 $d_string에 치환
pring "REPEAT $repeat times : $d_string\n";

 

 



- 예제 (2)

 

#!/usr/local/bin/perl
print '007',' has been portrayed by at least ', 004, ' actors. ';
print 7+3, ' ', 7*3, ' ', 7/3, ' ', 7%3, ' ', 7**3, ' ';
$x = 7;
print $x;
print ' Doesn\'t resolve variables like $x and backslashes \n. ';
print "Does resolve $x and backslash\n";
$y = "A line containing $x and ending with line feed.\n";
print $y;
$y = "Con" . "cat" . "enation!\n";
print $y;

 

 



< 출력 결과 >
007 has been portrayed by at least 4 actors. 10 21
2.3333333333333335 1 343 7
Doesn't resolve variables like $x and backslashes \n. Does
resolve 7 and backslash
A line containing 7 and ending with line feed.
Concatenation!


4. 배열
▣ 배열
- 데이타의 리스트
- 형식 :
'@'로 시작되며 문자와 숫자, 밑줄문자(_)가 뒤에 올수있다.
- 대문자와 소문자의 구별 (@a != @A), case sensitive
- 스칼라변수와의 구별 ($a != @a)
▣ 데이타의 리스트
- 데이타 : $a[0], $a[1], $a[2], ... ,$a[n]
리스트 : @a == ($a[0], $a[1], $a[2], ... ,$a[n])
$n[0]=23;
$n[1]="abc;
@n=(23,"abc");
@n=($a,$b,$c);
($a,$b,$c)=(1,2,3);
- 예제

 

#!/usr/local/bin/perl
# array example (1)
@a = (1,2,3); # @a에 1,2,3을 저장 # $a[0] = 1; $a[1] = 2; $a[2] = 3; 와 동일
print "Array value : @a\n";
print "Scalar value : $a[0] , $a[1] , $a[2]\n";


@string = ("Don\'t worry","Be happy!");
# @string에 Don't worry Be happy를 저장
# $string[0] = "Dont\t worry"; $string[1] = "Be
# happy!"; 와 동일
print "Array value : @string\n";
print "Scalar value : $string[0] , $string[1]\n";

 

 



▣ 데이타의 형
- 배열에 저장되는 데이타의 형(type)은 관계없다.
- 배열의 수정

 

#!/usr/local/bin/perl
# array example (2)
@b = (1,"two"); # $b[0] = 1; $b[1] = "two"; 과 동일
print "Array value : @b\n";
print "Scalar value : $b[0] , $b[1]\n";
$b[0]++;
# $b[0]값을 1만큼 증가
# 따라서, @b = (2, "two")
print "Array value : @b\n";
print "Scalar value : $b[0] , $b[1]\n";

$b[0] = "one"; # 수정-> @b = ("one","two")
print "Array value : @b\n";
print "Scalar value : $b[0] , $b[1]\n";

 

 


▣ 삽입과 삭제
- 배열의 삽입

 

#!/usr/local/bin/perl
# array example (3)
@name = ("Kim", "Lee", "Park");
print "NAME : @name\n";

@name_plus = ("Jeong", @name, "Kang");
# @name_plus=("Jeong", "Kim", "Lee", "Park", "Kang");
# 와 동일
print "NAME_PULSE : @name_plus\n";

 

 



- 배열의 PUSH, POP
PUSH : 배열의 마지막 데이타로 추가한다.
POP : 배열의 마지막 데이타를 가져온다.

 

#!/usr/local/bin/perl
# array example (2)
@food = ("apples", "pears", "eels");
pint "FOOD : @food\n";

push(@food, "eggs","banana");
# 데이타 eggs, banana를 배열 @food에 Push한다.
# @food=("apples", "pears", "eels", "eggs","banana");
# 와 동일한 결과
print "FOOD + eggs + banana : @food\n";

$food_item1 = pop(@food);
# @food의 마지막 데이타(banana)를 $food_item1에
# Pop한다.
# @food = ("apples", "pears", "eels", "eggs");
# 와 동일한 결과
print "FOOD : @food , ITEM1 : $food_item1\n");

 

 


▣ 기타
- 배열의 길이계산 : $length = @array;
- 배열의 데이타 -> 문자열 : $string = "@array";
- 배열의 다중치환
($a, $b) = @array;
# @array의 처음 2개의 데이타가 $a와 $b에 각각 치환된다.
($a, @b_array) = @array;
# @array의 처음 데이타가 $a에, 나머지 데이타가
# @b_array에 각각 치환된다.


5. 입출력문
▣ 표준 입출력
- 입력 : , open(INPUT, '-')
$line=;
chop($line);
$line=~tr/a-z/A-Z/; print "$line\n";

chop($line=);
$line=~tr/a-z/A-Z/; print "$line\n";

$_=; chop;
tr/a-z/A-Z/; print "$_\n";

while(){
chop;
tr/a-z/A-Z/; print "$_\n";
}

@n=;
foreach (@n){
chop;
tr/a-z/A-Z/; print "$_\n";
}
- 출력 : print, open(OUTPUT, '>-')
print "Hi";
print "Hi\n";
print "This is line 1\nThis is line 2\n";

$first="Dave"; $last="Molta";
$name="$first $last";
$name=$first." ".$last;
$name.=" III";
print "My boss's name is $name.\n";
print 'The variable $name holds '.$name."\n";
print 'His name is stored in the variable name $name.'."\n";
print "1\t2\t3\t4\t5\n";

printf("%s %s\n",$name,$date);
$namedate=sprintf("%s %s\n",$name,$date);

- 예제 (1)

 

 

#!/usr/local/bin/perl
# standard i/o example(1)
print "Input : ";
$agv = ;
print "$agv";
 

 

 



- 예제 (1)

 

#!/usr/local/bin/perl
# standard i/o example(2)
print STDOUT "Tell me something: ";
while ($input = ) {
print STDOUT "You said, quote: $input endquote\n";
chop $input;
print STDOUT "Without the newline: $input endquote\n";
if ($input eq '') { print STDERR "Null input!\n"; }
print STDOUT "Tell me more, or ^D to end:\n";
}
print STDOUT "That's all!\n";
 

 

 



▣ 파일 입출력
- 입력
open(INPUT, $file);
open(INPUT, "<$file");
- 출력
open(OUTPUT, ">$file");
open(OUTPUT, ">>$file");

open(MYOUT,">myoutputfile.txt");
print MYOUT "Hello.\n";
close(MYOUT);

open(MYFILE,"){
chop;
tr/a-z/A-Z/; print "$_\n";
}

while(<>){
chop;
tr/a-z/A-Z/; print "$_\n";
}

while(){
chop;
tr/a-z/A-Z/; print "$_\n";
}

- 예

 

 

#!/usr/local/bin/perl
# file i/o example
# program to open the passwd file
$file='/etc/passwd';
# 유닉스에서의 패스워드파일 설정
open(INFO, $file); # 파일열기(입력옵션)
@lines=; # 파일의 끝까지 배열 @line에 저장
close(INFO); # 파일닫기
print @lines; # @line의 내용을 화면에 출력
 

 

 



▣ 입출력문 예제
- 유닉스에서의 cat과같은 동작을 하는 프로그램을 작성하여라.
- 표준입력으로 파일이름(test.cat)을 입력
- 파일입력으로 해당파일의 내용을 배열 @lines에 저장
- 표준출력으로 @lines을 출력
- test.cat 파일내용, (계속 사용될 파일임)
aaaabcaaaaaaaaaaaa
bbbb

dddddabcdddddddddddddabcddddddddddddddd
eeeeeeabc

gggggggggggggggggg
- 프로그램

 

#!/usr/local/bin/perl
# cat program
print "Input file name : ";
$file = ;
chop $file;
# 입력된 변수 $file의 개행(newline)문자 제거
open(INFO, "$file") || die "\"$file"\" : $!\n";
# 파일열기(입력옵션)
# die : 파일이 없을시 오류메세지 출력
@lines=;
# 파일의 끝까지 배열 @line에 저장
close(INFO); # 파일닫기
print @lines; # @line의 내용을 화면에 출력
 

 

 



6. 제어문, 조건문
▣ for 문
- 형식
for(초기값 ; 테스트 ; 증가식)
{
문장1;
문장2;
}

for($i=0; $i<2; $i++)
{print $n[$i];}

- 예제 (1부터 10까지 표준출력)
for ($i = 0 ; $i < 10 ; ++$i)
{
print "$i\n";
}
▣ foreach 문
- foreach의 { }안에서 변수의 처리
- 형식
foreach 변수 (식)
{
문장1;
문장2;
}

@n=(1,2);
foreach $i (0..1) {print $n[$i];}
foreach $i (@n) {print $i;}
foreach (@n) {print $_;}
foreach (@n) {print;}

- 예제
@array = ("1","b","c","d");
foreach $item (@array)
# @array의 데이타가 $item에 하나씩 치환된다.
{
print "$item : ";
$item = $item . 100;
# $item에 100을 추가(append)
print "$item\n";
}
▣ while , do while 문
- while문
- 형식
while (테스트)
{
문장1;
문장2;
}

$i=0;
while ($i<2)
{print $n[$i];
$i++;}

- 예제 (입력스트링이 test일때까지 반복수행)
print "Input string : ";
$input=>;
chop $input;
while($input ne "test")
{
print "\tsorry, again? ";
# \t : TAB키의 특수문자
$input=;
chop $input;
}
- do while문
- 형식
do
{
문장1;
문장2;
} while (테스트)
- 예제 (입력스트링이 test일때까지 반복수행)
do
{
print "Input string : ";
$input=;
chop $input;
} while($input ne "test")
▣ if 문
- 형식
if(조건식)
{ 문장; }
else
{ 문장; }

if(조건식1)
{ 문장; }
elsif(조건식2)
{ 문장; }
elsif(조건식3)
{ 문장; }

if($a eq "hello"){$z="goodbye";}
else{$z="bye";}

if($a == 2){$z=$a+1;}

if($a = 1){$z=$a+1;} #Wrong!

- 예제
print "Input Chracter : ";
$input=;
chop $input;
if(!$input) # 입력스트링이 공백이었을때
{ print "empty!!!\n"; }
elsif(length($input) == 1 )
# length() : 스트링의 길이를 계산
{ print " 1 character.\n"; }
elsif(length($input) == 2 )
{ print " 2 chracter.\n"; }
else
{ print "a lot of character.\n"; }

▣ 제어문, 조건문 예제
- 5. 입출력문(입출력문 예제)에서 제시된 프로그램(cat
프로그램)에서 출력시 라인번호를 함께 출력하는 프로그램을
작성하여라.
- 출력
1 : aaaabcaaaaaaaaaaaa
2 : bbbb
3 :
4 : dddddabcdddddddddddddabcddddddddddddddd
5 : eeeeeeabc
6 :
7 : gggggggggggggggggg
- 프로그램

 

 

#!/usr/local/bin/perl
# cat program + line number
print "Input file name : ";
$file = ;
chop $file;
# 입력된 변수 $file의 개행(newline)문자 제거
$count = 1; # 라인번호 초기화
open(INFO, $file);
while($line = ) # 라인단위로 $line에 입력받음
{
print "$count : $line";
++$count;
}
close(INFO);
 

 

 



7. 정규표현식
▣ 간단한 예제
- 표준입력으로 받은 스트링에 "test" 가 있으면 문장을
수행하는 프로그램

 

#!/usr/local/bin/perl
while(<>)
{
if(/test/)
{ print "exist \"test\"!!!\n"; }
}

 

 



▣ 해설
- while(<>) : while($_ = )과 동일
- if(/test/)
: 정규표현은 슬레쉬(/)사이에 쓰여진다.
: 변수명을 지정하지 않을경우 기본변수인 $_를 비교한다.
: if($_ =~ /test/) 와 동등
: 입력스트링중에 test가 포함되어있을경우 { }를 수행
- 동작
: 입력에 "This is a tes t!!!" 일경우 { }를 수행하지 않음
: 입력에 "This is a test!!!" 일 경우 { }를 수행
▣ 정규표현식
- 강력한 표현능력
- 슬레쉬(/)사이에 쓰여진다.
- 표현
. # 개행(newline)을 제외한 한문자
^ # 라인또는 스트링의 시작
$ # 라인또는 스트링의 끝
* # 0 또는 여러개의 문자
+ # 1 또는 여러개의 문자
? # 0 또는 1개의 문자
- 표현예
t.e
# t와 e사이의 어떤 한문자가 들어간 스트링
# the, toe, tre등등
^ftp # ftp가 라인의 시작인 스트링
es$ # es가 라인의 끝인 스트링
und*
# un다음에 0또는 d가 여러개 나오는 문자
# un
# und
# undd
# unddd 등등
.* # 개행없는 스트링
^$ # 공백 라인
▣ 정규표현식 옵션
- '['와 ']'사이에서 표현된다.
- '-' : 사이(Between)를 의미
- '^' : Not을 의미
- '|' : 또는(Or)을 의미
- '()' : 그룹을 의미
- 표현식 옵션예
[qjk] # q또는 j또는 k
[^qjk] # q또는 j또는 k은 제외
[a-z] # 소문자중의 하나
[^a-z] # 소문자는 제외한
[a-zA-Z]# 소문자, 대문자중의 하나
[a-z]+ # 최소 하나의 소문자를 포함한 소문자스트링
kim|lee # kim 또는 lee
(eg|le)gs # eggs 또는 legs
(da)+ # da 또는 dada 또는 dadada 등등
▣ 특수문자와 그외
\n # 개행
\t # tab
\w # 알파벳 문자
# 정규표현 [a-zA-Z0-9_]와 동일
\W # 알파벳 문자가 아닌 문자
# 정규표현 [^a-zA-Z0-9_]와 동일
\d # 숫자, 정규표현 [0-9]와 동일
\D # 숫자가아닌 문자, 정규표현 [^0-9]와 동일
\s # 공백문자
\S # 공백문자가 아닌 문자

\| # '|'
\[ # '['
\) # ')'
\* # '*'
\^ # '^'
\/ # '/'
\ # '\'
▣ 정규표현에서의 비교
- Equal : =~
- Nont Equal : !~

$n=~/\smyfile=(\S+)\s/;

if($n=~/\smyfile=(\S+)\s/){$myfile=27240;}

$n=~/^(\S+)\s+(\S)$/;

while(<>){
chop;
/^(\S+)\s+(\S+)$/;
print "17072\t27240\n";
}

if(/mystring/){$x=1;}

if($line=~/mystring/){$x=1;}

if($line!~/mystring/){$x=1;}

/file=(\w+\s)/;
$file=27240;

if(/file=(\w+)\s/){$file=27240;}
- 예

 

 

#!/usr/local/bin/perl
$a = "This is a pen!";
$b = "I'm a boy.";
if ($a =~ /is/)
{ print "exist \"is\"!!!\n"; }
if ($b !~ /am/)
{ print "Not exist \"am\"!!!\n"; }

 

 



▣ 정규표현식 예제
- 6. 제어문, 조건문(제어문, 조건문 예제)에서 제시된 프로그램(cat
프로그램)에서 출력시 라인번호를 함께 출력하는 프로그램을
작성하되 공백라인은 출력하지말것.
- 출력
1 : aaaabcaaaaaaaaaaaa
2 : bbbb
3 : dddddabcdddddddddddddabcddddddddddddddd
4 : eeeeeeabc
5 : gggggggggggggggggg
- 프로그램

 


#!/usr/local/bin/perl
# cat program + line number + NO empty line
print "Input file name : ";
$file = ;
chop $file;
# 입력된 변수 $file의 개행(newline)문자 제거
$count = 1; # 라인번호 초기화
open(INFO, $file);
while($line = # 라인단위로 $line에 입력받음
{
if( $line !~ /^$/) # 정규표현 ^$는 공백라인
# 공백라인이 아닌경우 { } 수행
{
print "$count : $line";
++$count;
}
}
close(INFO);
 

 

 




8. 문자의 대용과 변환
▣ seoul을 SEOUL로 대용
- s 함수사용 : s/(대용할 문자)/(대용될 문자)/(옵션)
- 슬레쉬(/)사이에서 정규표현이 사용될수있다.
- $string =~ s/seoul/SEOUL/;
변수 $string에 저장된 문자열의 첫번째 seoul을 SEOUL로
대용한다.

 

#!/usr/local/bin/perl
$string = "seoul, seoul, seoul, korea";
$string =~ s/seoul/SEOUL/;
print "$string\n";
# 출력은 SEOUL, seoul, seoul, korea이 된다.

 

 

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com



▣ 옵션
- 마지막 슬레쉬(/)뒤에 옵션을 넣을수 있다.
- g 옵션 : 해당 문자열의 전체적인 대용을 한다.
- $string =~ s/seoul/SEOUL/g;

 

#!/usr/local/bin/perl
$string = "seoul, seoul, seoul, korea";
$string =~ s/seoul/SEOUL/g; # 전체적 대용
print "$string\n";
# 출력은 SEOUL, SEOUL, SEOUL, korea이 된다.

 

 



- i 옵션 : 대문자, 소문자무시
- $string =~ s/SeouL/SEOUL/i;
- 정규표현 : $string =~ s/[Ss][Ee][Oo][Uu][Ll]/SEOUL/;

 

#!/usr/local/bin/perl
$string = "seoul, seoul, seoul, korea";
$string =~ s/SeouL/SEOUL/gi;
# 대소문자무시, 전체적 대용
print "$string\n";
# 출력은 SEOUL, SEOUL, SEOUL, korea이 된다.

 

 



▣ 문자의 대용예제
- 7. 정규표현식(정규표현식 예제)에서 제시된 프로그램에서
소스파일(test.cat)의 내용중 abc가 들어간 문자를 로
대용하여 출력하는 프로그램을 작성하라.
- 출력
1 : aaaaaaaaaaaaaaa
2 : bbbb
3 : ddddddddddddddddddddddddddddddddd
4 : eeeeee
5 : gggggggggggggggggg
- 프로그램

 

 

#!/usr/local/bin/perl
# cat program + line number + NO empty line + replace
print "Input file name : ";
$file = ;
chop $file;
# 입력된 변수 $file의 개행(newline)문자 제거
$count = 1; # 라인번호 초기화
open(INFO, $file);
while($line = ) # 라인단위로 $line에 입력받음
{
if( ($line !~ /^$/) && ($line =~ s/abc/\/g) )
# 정규표현 ^$ 는 공백라인
# abc를 로 전체적으로 대용
# 공백라인이 아닌경우 { } 수행
{
print "$count : $line";
++$count;
}
}
close(INFO);
 

 

 



▣ 대문자를 소문자로 변환
- tr 함수사용 : s/(변환할 문자)/(변환될 문자)/
- 슬레쉬(/)사이에서의 특수정규표현은 사용될수없다. (단, 사이를
의미하는 '-'는 가능)
- 문자 대 문자로 변환
: tr/abc/def/;
: a는 d로, b는 e로, c는 f로 변환된다.

$m=~tr/abcdefghiklmnoprstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/;
$m=~tr/a-z/A-Z/;
- $string =~ tr/ A-Z/a-z/;

 

#!/usr/local/bin/perl
print "Input string : ";
$string=;
chop $string;
# 입력된 변수 $string의 개행(newline)문자 제거
$count = ($string =~ tr/A-Z/a-z/);
# 대문자를 소문자로 변환
# 변환된 문자의 갯수를 $count에 치환
print "$count numbered : $string\n";
 

 

 



9. 기본 함수
▣ split( )
- 형식 : (배열) = split( /(구분문자)/, (스트링) )
- 해당 스트링을 배열로 나눔
- (스트링)이 지정되지 않을경우 기본변수($_)를 처리한다.
- 정규표현이 사용될수있다.
chop($n=);
@n=split(/ /,$n);
@n=split(/,/,$n);
@n=split(/\t/,$n);
@n=split(/\s+/,$n);
@n=split(/\s+0*/,$n);
($first,$middle,$last)=split(/\s+/,$n);

- 간단한 예제(1)

 

 

#!/usr/local/bin/perl
# split() example (1)
$string = "Hong Gil-Dong::Male::19::Korea";
@array = split(/::/, $string);
# $string의 내용을 '::' 로 구분하여 배열 @array에 저장
# @array = ("Hong Gil-Dong","Male","19","Korea");
# 와 동일
print "$string = @array\n";

 

 



- 위의 예제에서,
$string = "Hong Gil-Dong::Male:::19:Korea"; 일 경우
@array = "Hong il-Dong","","Male","","","19","Korea");
와 동일
- 간단한 예제(2) : 정규표현사용

 

#!/usr/local/bin/perl
# split() example (2)
$string = "Hong Gil-Dong::Male:::19:Korea";
@array = split(/:+/, $string);
# 정규표현 /:+/ 은 ':'이 한번또는 여러번 나오는 문자를
# 의미
# $string의 내용을 ':' 또는 '::' 또는 ':::' ..
# '::::::'등으로 구분하여 배열 @array에 저장
# @array = ("Hong Gil-Dong","Male","19","Korea");
# 와 동일
print "$string = @array\n";

 

 



▣ join( )
- 형식 : (스트링) = join( "(연결문자)", (배열) )
- 해당 배열을 스트링으로 연결

@n=(1,2,3,4,5);
$n=join(" ",@n);
print "$n\n"; #Gives 1 2 3 4 5

$n=join("\t",@n);
print "$n\n"; #Gives 1 2 ...

$n=join(",",@n);
print "$n\n"; #Gives 1,2,3,4,5
- 간단한 예제(1)

 

#!/usr/local/bin/perl
# join() example (1)
$string =join(":::","This","is","a","join","function");
# $string = "This:::is:::a:::join:::function" 과 동일
print "$string\n";

 

 



- 간단한 예제(2)

 

#!/usr/local/bin/perl
# join() example (2)
@array = ("Hong Gil-Dong","Male","19","Korea");
$string = join("::", @array);
# $string = "Hong Gil-Dong::Male::19::Korea"; 와 동일
print "$string\n";

 

 



- 간단한 예제(3)

 

#!/usr/local/bin/perl
# join() example (3)
@stuff = ('This', 'is', 'a', 'list.');
print "Lists and strings are indexed from 0.\n";
print "So $stuff[1] = $stuff[1], ",
"and $#stuff = $#stuff.\n";
# 베열 @stuff의 두번째 데이타인 "is"를 출력한다.
print @stuff,"\n";
print join('...',@stuff),"\n";
splice(@stuff, 3, 0, ('fine', 'little'));
# 배열 @stuff의 4번째 부터 "fine"과 "little"를 차례로 삽입
print join('...',@stuff),"\n";
# 배열 @stuff를 "..."로 join하여 출력

 

 



<출력 결과>
Lists and strings are indexed from 0.
So $stuff[1] = is, and $#stuff = 3.
Thisisalist.
This...is...a...list.
This...is...a...fine...little...list.

▣ substr( )
- 형식 : (스트링) = substr((스트링), 시작, 길이);
- 해당 스트링에서 원하는 스트링의 뽑아냄
- $string = substr("Once upon a time", 3, 4);
# "e up"을 $string 에 치환
$string = substr("Once upon a time", 7);
# "on a time"을 $string 에 치환
$string = substr("Once upon a time", -6, 5);
# "a tim"을 $string 에 치환
▣ length( )
- 형식 : (변수) = length((스트링));
- 스트링의 길이계산
- 간단한 예제

 

#!/usr/local/bin/perl
# length() example
$count = length("This is a length function");
print "$count\n";
# "This is a length function"의 길이 13을 출력

 

 



10. 결합배열
▣ 결합배열
- 배열의 결합
- 형식 :
'%'로 시작되며 문자와 숫자, 밑줄문자(_)가 뒤에 올수있다.
- 대문자와 소문자의 구별 (%a != %A), case sensitive
- 예 (이름과 나이의 결합배열)

%persons = ( "Hong Gil-Dong", 20,
"Lee Young-Ho", 13,
"Kim Sun-Hee", 28,
"Park Cheol-Su", 40 )
# "Park Cheol-Su"은 Keys, 40은 Values

$ages = $persons{"Hong Gil-Dong"};
# 20을 $ages에 치환
$ages = $persons{"Lee Young-Ho"};
# 13을 $ages에 치환
$ages = $persons{"Park Cheol-Su"};
# 40을 $ages에 치환
▣ 결합배열 & 배열
- 배열 : 수치에 의한 접근, [ ]로 접근
ex) @array의 첫번째 원소: $array[0]
@array의 두번째 원소: $array[1]
- 결합배열 : Keys 에 의한 접근, { }로 접근
ex) $persons{"Hong Gil-Dong"};
$persons{"Kim Sun-Hee"};
- 결합배열 -> 배열
@array = %persons;
# 배열 @array에는 8개의 원소가 있다.
$array[4]; # $array[4]은 13이다.
- 배열 -> 결합배열
%morepersons = @array;
# %morepersons는 %persons과 동일


11. 서브루틴
▣ 간단한 예제
&add5toa;

sub add5toa {
$a+=5;
}
- 프로그램

 

#!/usr/local/bin/perl
# subroutine example
sub print_hello
{
print "hello\n";
}
sub print_name
{
print "How are you? $_[0]!!!\n";
}
sub print_bye
{
print "bye!!!\n";
}

&print_hello; # 서브루틴 호출
&print_name("kim"); # 매개변수 호출
&print_bye;

 

 



- 해설
: 서브루틴은 프로그램의 어디든지 위치할수있다.
: 호출시 서브루틴이름 앞에 &이 추가된다.
▣ 매개변수 호출과 복귀값
- 메인프로그램에서 서브루틴을 호출할때에는 다음의
2가지경우가 있다.
: 매개변수 없는 호출 예) &print_hello;
: 매개변수 호출 예) &print_name("Kim");
- 복귀값
: 서브루틴에서 마지막으로 계산되어진 값

 

#!/usr/local/bin/perl
# subroutine example - return value
sub maximum
{
if($_[0] > $_[1])
{ $_[0];}
else
{ $_[1];}
}

$result = &maixmum(100,99);
print "Maixmum value : $result\n";

 

 



: $_[0]으로 100이, $_[1]으로 99가 서브루틴에 전달된다.
: $result에는 서브루틴의 복귀값인 $_[0]값 즉, 100이 치환된다.
▣ 지역변수
- @_과 $_[0],$_[1],.. $_[n]등과 같은 지정된 지역변수외에
사용자가 지정한 지역변수를 서브루틴에서 사용할수있다.
- 형식 :
local(서브루틴에서의 변수이름) = ( 매개변수이름 )

$ans=&sumthree(5,11,22);

sub sumthree {
local($a,$b,$c)=@_;
return($a+$b+$c);
}

- 예

 

#!/usr/local/bin/perl
# subroutine example - local variables
sub print_sum
{
local($a, $b,) = ($_[0], $_[1]);
# 전달된 $_[0], $_[1]를 서브루틴에서 $a, $b로 사용하였다.
return ($a + $b);
# $a와 $b를 더한값을 복귀값으로 하였다.
}

$a = 100;
$b = 200;
print &print_sum(123,456);
# 123과 456을 서브루틴 &print_sum로 호출한뒤,
# 복귀값 579를 출력한다.
print "\n $a = $a , $b = $b\n";
# $a와 $b는 100과 200이 출력된다.
# 서브루틴의 $a와 $b는 지역변수이다.

 

 

 





3 Perl 프로그래밍 활용


1. 사용자 정보
▣ 해설
- 유닉스명령어 'w'또는 'who'와 같은 동작을 하는 스크립트
- 유닉스에서의 기본 명령인 hostname과 uptime 그리고 w -w를
이용.
- "`"로 묶여진것은 유닉스(혹은 해당 OS)의 명령어를 수행한다.
- 출력 결과
xxxx Status
12:14pm up 6 day, 5:58, 4 users, load average: 0.08, 0.21,
0.53
marie pts/135 hirc ???? mail.kornet.nm.kr
brhee pts/117 slirp -P -b 38400
pyong pts/17 tia
elegy pts/122 -csh

▣ 프로그램

 

#!/usr/local/bin/perl
# Status viewr (1)
$host = `hostname`;
chop $host;
$uptime = `uptime`;
$w = `w -w`;
print "$host Status\n";
print "$uptime\n";
print "$w\n";
exit;

 

 



▣ system( ) 사용
- "`"를 사용치않고 system( )을 활용한 예제

 


#!/usr/local/bin/perl
# Status viewr (2)
system "hostname";
system "w -w";
exit;

 

 




- system( )을 이용하면, 유닉스상에서 사용되는 모든 명령어를
프로그램에 쉽게 활용할수있다.

2. 계산기
▣ 해설
- 쉘과 수치계산기의 동작
- 출력 결과
%cal.pl
() ? dsa
(dsa) ? 5+7
(12) ? date
(date) ? date
(date) ? ^@ = date
([undefined]) ? $x=`date`
(1996년 2월 12일 월요일 오전 12시 54분 51초
) ? chop $x
(
) ? $x
(1996년 2월 12일 월요일 오전 12시 54분 51초) ? exit
%
▣ 프로그램

 

#!/usr/local/bin/perl
# Calculator
while(1) {
print "($result) ? ";
last unless $Input = ;
$result = eval $input;
if ($@) { print $@ }
if (! defined($result)) { $result='[undefined]' }
}
 

 

 




3. 디스크사용량 정보
▣ 해설
- 특정파일혹은 디렉토리의 사용량을 확인
- 유닉스명령어 "du -sk"와 같은 동작을 하는 프로그램
- 용량은 K bytes단위로 파일과 디렉토리를 표시한다.
- 소유주가 다른 파일이나 디렉토리나 그것의 수정날짜등의
정보는 표시되지않음
- 출력 결과

K-bytes Login Name Modified File
40788 c527100 Fred Flintstone 95-10-05 c527100
32685 c565060 Peter Parker 95-10-05 c565060
24932 c579818 Clark Kent 95-10-06 c579818
15388 c576657 Lois Lane 95-10-06 c576657
9462 c572038 Bruce Wayne 95-10-06 c572038
8381 c517401 Eric McGregor 95-10-05 c517401
7022 c594912 Asterisk de Gaul 95-10-05 c594912
▣ 프로그램

 

#!/usr/local/bin/perl
# Disk usage utility
$files = join(' ',@ARGV);

# 해당 파일혹은 디렉토리를 "du"명령어로 처리
# 마지막의 "|"는 결과 내용을 프로램의 입력으로 쓰기위한것.
if (! open (DUPIPE,"du -sk $files | sort -nr |")) {
die "Can't run du! $!\n";
}

# 출력 형식
printf"%8s%-8s%-16s %8s%s\n",'K-bytes','Login','Name','Modified','File';

while () {
# "du" 명령어로 처리된 데이타를 용량과 파일이름으로 나눔
($kbytes, $filename) = split;

# 해당파일에 대한 정보를 각 변수에 치환
($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,
$size,$atime,$mtime,$ctime) = stat($filename);

# 사용자의 아이디와 이름, uid를 저장
if ($uid != $previous_uid) {

($login,$passwd,$uid,$gid,$quota,$comment,$realname,$dir,$shell)
= getpwuid($uid);
($realname) = split(',',substr($realname,0,20));
$previous_uid = $uid;
}

# 파일이나 디렉토리의 수정된 날짜처리
($sec,$min,$hour,$mday,$mon,$myear) = localtime($mtime);
$mmonth = $mon+1;
printf "%8s %-8s %-16s %02s-%02d-%02d %s\n",
$kbytes, $login, $realname,
$myear, $mmonth, $mday, $filename;
}
 

 

 



4. 전화번호 검색
▣ 해설
- 전화 교환시스템이 있는 회사의 전화번호 검색
- 영문과 국문으로 모두 검색가능
- 국번은 공통적으로 123이다.
- 데이타 파일(phone.dat) 형식

서무계:::General Affairs Charge:::7028
구매계:::Purchase Charge:::7029
관리계:::Management Charge:::7033
경리과:::Accountant' Section:::7030
시설과:::Equipment Department:::7052
전산실:::Computing Center:::7042
- 출력 결과
%search
Search String : 계
Korean? (y|n) : y
Result( 계 ) :
서무계 : 02-123-7028
구매계 : 02-123-7029
관리계 : 02-123-7033
%

▣ 프로그램

 

#!/usr/local/bin/perl
$file = "phone.dat";

print "Search String : ";
$search = ;

print "Korean? (y|n) :";
$type = ;

chop $search;
chop $type;

print "\tResult( $search ) : \n";

open(PHONE,"$file") || die "\"$file\" : $!\n";
# 전화 데이타파일을 오픈

while($line=) # 라인별로 입력을 받는다
{
@item=split(/:::/,$line);
if($type =~ /y/)
# 한글로 검색할때
{
if($item[0] =~ /$search/)
{
print "\t$item[0] : 02-123-$item[2]";
}
}
elsif($type =~ /n/)
# 영문으로 검색할때
{
if($item[1] =~ /$search/)
{
print "\t$item[1] : +82-02-123-$item[2]";
}
}
}
close(PHONE);
 

 

 



5. 성적평가
▣ 해설
- 성적평가 프로그램
- 결합배열과 분류(sort)를 이용하여 보고형식으로 출력한다.
- 학생의 인적파일과 성적파일을 사용한다.
- 학생들의 이름순(알파벳)으로 분류(sort) 처리하였다.
- 입력파일 형식
: 학생인적 파일 stufile은 학번, 이름, 학년별로 ':'으로 구분되어
입력된다.

123456:Washington,George:SR
246802:Lincoln,Abraham "Abe":SO
357913:Jefferson,Thomas:JR
212121:Roosevelt,Theodore "Teddy":SO

: 학생성적 파일 "scorefile"은 학번, 과목번호, 성적이 공백으로
구분되어진다. Abe 는 두번째
시험에 결시하였다.

123456 1 98
212121 1 86
246802 1 89
357913 1 90
123456 2 96
212121 2 88
357913 2 92
123456 3 97
212121 3 96
246802 3 95
357913 3 94

- 출력 결과
Stu-ID Name... 1 2 3 Totals:

357913 Jefferson,Thomas 90 92 94 276
246802 Lincoln,Abraham "Abe" 89 95 184
212121 Roosevelt,Theodore "Teddy" 86 88 96 270
123456 Washington,George 98 96 97 291

Totals: 363 276 382

▣ 프로그램

 

#!/usr/local/bin/perl

$stufile='stufile'; # 학생인적 파일지정
$scorefile='scorefile'; # 성적 파일지정

# 파일이 성공적으로 열리면 수행하되,
# 그렇지 않는경우 '||'이하를 수행한다.
open (NAMES,"<$stufile") || die "Can't open $stufile $!";
open (SCORES,"<$scorefile") || die "Can't open $scorefile $!";

# 학번을 이용하여 학생의 정보를 결합배열로 생성한다.
while () {
($stuid,$name,$year) = split(':',$_);
$name{$stuid}=$name;
if (length($name)>$maxnamelength) {
$maxnamelength=length($name);
}
}
close NAMES;

# 입력받은 성적으로부터 표를 생성한다.

while () {
($stuid,$examno,$score) = split;
$score{$stuid,$examno} = $score;
if ($examno > $maxexamno) {
$maxexamno = $examno;
}
}
close SCORES;

# 최종적으로 입력된 데이타를 보고형식으로 출력한다.

printf "%6s %-${maxnamelength}s ",
'Stu-ID','Name...';
foreach $examno (1..$maxexamno) {
printf "%4d",$examno;
}
printf "%10s\n\n",'Totals:';

# 서브루틴 'byname'은 결합배열 %name으로 부터 이름을 분류.
# 함수 "sort"는 주어지는 변수 $a와 $b를 사용한다.
# "x cmp y" 은 xy일경우 +1의 복귀값을 가진다.

sub byname { $name{$a} cmp $name{$b} }

# 학생이름의 알바벳순으로 처리
foreach $stuid ( sort byname keys(%name) ) {
# 학생들의 과목별성적과 총점수를 출력
printf "%6d %-${maxnamelength}s ",$stuid,$name{$stuid};

$total = 0;
foreach $examno (1..$maxexamno) {
printf "%4s",$score{$stuid,$examno};
$total += $score{$stuid,$examno};
$examtot{$examno} += $score{$stuid,$examno};
}
printf "%10d\n",$total;
}

printf "\n%6s %${maxnamelength}s ",'',"Totals: ";
foreach $examno (1..$maxexamno) {
printf "%4d",$examtot{$examno};
}
print "\n";
exit(0);
 

 

 

 







[1] Larry Wall and Randall L.Schwartz,"Programming Perl",ISBN 0-937175-64-1,
O'Reilly & Associates, Inc., 1991

[2] Randal L. Schwartz, "Learning Perl",ISBN 1-56592-042-2,
O'Reilly and Associates, Inc.,1993

[3] Ellie Quigley, "Perl by Example", ISBN 0-13-122839-0, 1993

[4] "Teach Yourself Perl in 21 Days", SAMS Publishing, ISBN 0-672-30586-0,

[5] Introduction to Perl or, Learn Perl in Two Hours
http://www.phlab.missouri.edu/perl/perlcourse.html

[6] "The PERL programming language" - Info, Scripts, Source, and Stuff
http://www.metronet.com/perlinfo/

[7] "PERL -- Practical Extraction and ReportLanguage"
http://www.cis.ufl.edu/cgi-bin/plindex

[8] The University of Florida Perl Archive
http://www1.cis.ufl.edu/perl/

[9] Tutorial "Perl for Generation of HTML "
http://www.cc.gatech.edu/grads/c/David.Carlson/html/perl.tutorial.html

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
1195 [ 一日30分 인생승리의 학습법] VBA Web Scraping: How Can VBA Be Used To Scrape Website Data? file 졸리운_곰 2024.04.13 3
1194 [ 一日30分 인생승리의 학습법] 윈도우 실행파일 구조(PE파일) file 졸리운_곰 2024.03.31 3
1193 [ 一日30分 인생승리의 학습법] [Analysis] PE(Portable Executable) 파일 포맷 공부 file 졸리운_곰 2024.03.31 3
1192 [ 一日30分 인생승리의 학습법] 성공하는 메타버스의 3가지 조건 file 졸리운_곰 2024.03.30 7
1191 [ 一日30分 인생승리의 학습법] REST, REST API, RESTful 과 HATEOAS file 졸리운_곰 2024.03.10 9
1190 [ 一日30分 인생승리의 학습법] 렌더링 삼형제 CSR, SSR, SSG 이해하기 file 졸리운_곰 2024.03.10 2
1189 [ 一日30分 인생승리의 학습법] 엑셀 VBA에서 셀레니움 사용을 위한 Selenium Basic 설치 file 졸리운_곰 2024.02.23 11
1188 [ 一日30分 인생승리의 학습법]500 Lines or Less Blockcode: A Visual Programming Toolkit : 500줄 이하의 블록코드: 시각적 프로그래밍 툴킷 졸리운_곰 2024.02.12 4
1187 [ 一日30分 인생승리의 학습법] 구글 클라이언트(앱) 아이디를 발급받으려면 어떻게 해야 하나요? 졸리운_곰 2024.01.28 3
1186 [ 一日30分 인생승리의 학습법] 빅뱅 프로젝트를 성공적으로 오픈하기 위한 팁 졸리운_곰 2023.12.27 16
1185 [ 一日30分 인생승리의 학습법]“빅뱅 전환보다 단계적 전환 방식이 이상적 애자일팀과 협업 쉽게 체질 개선을” file 졸리운_곰 2023.12.27 12
1184 [ 一日30分 인생승리의 학습법] Big-bang / phased 접근 file 졸리운_곰 2023.12.27 3
1183 [ 一日30分 인생승리의 학습법] CodeDragon 메뉴 데이터 전환의 개념 이해 - 데이터 전환의 개념, 데이터 전환방식, 데이터 전환방식 및 장단점 비교, 데이터전환 이후 검토해야 할 사항 졸리운_곰 2023.12.27 5
1182 [ 一日30分 인생승리의 학습법] 블록체인과 IPFS를 이용한 안전한 데이터 공유 플랫폼 - 분쟁 해결 시스템 file 졸리운_곰 2023.12.27 6
1181 [ 一日30分 인생승리의 학습법] 블록체인과 IPFS를 이용한 안전한 데이터 공유 플랫폼 - 개념과 리뷰 시스템 file 졸리운_곰 2023.12.27 4
1180 [ 一日30分 인생승리의 학습법] 소켓 CLOSE_WAIT 발생 현상 및 처리 방안 file 졸리운_곰 2023.12.03 7
1179 [ 一日30分 인생승리의 학습법] robots 설정하기 졸리운_곰 2023.12.03 3
1178 [ 一日30分 인생승리의 학습법] A Tutorial and Elementary Trajectory Model for the Differential Steering System of Robot Wheel Actuators : 로봇 휠 액츄에이터의 차동 조향 시스템에 대한 튜토리얼 및 기본 궤적 모델 file 졸리운_곰 2023.11.29 6
1177 [ 一日30分 인생승리의 학습법] Streamline Your MLOps Journey with CodeProject.AI Server : CodeProject.AI 서버로 MLOps 여정을 간소화하세요 file 졸리운_곰 2023.11.25 2
1176 [ 一日30分 인생승리의 학습법] Comparing Self-Hosted AI Servers: A Guide for Developers / : 자체 호스팅 AI 서버 비교: 개발자를 위한 가이드 file 졸리운_곰 2023.11.25 10
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED