Monday, December 31, 2012

Perl 의 shift 와 unshift 함수

shift 는 array의 맨 앞에서 element 를 빼내고 (stack 의 pop 에 해당)
unshift 는 array의 맨 앞에 element 를 넣는다 (stack 의 push 에 해당).

Perl에서 두 array 를 합치는 법

 my @a = (1, 3, 5, 7);  
 my @b = (2, 4, 6, 8);  
 my @c = (@a, @b);  
 print(join(", ", @c) . "\n");  
키워드 : 합침, union

array 를 hexadecimal 의 string 으로 받는 함수

1:  sub atohexstring  
2:  {   
3:         my $s = "";  
4:         foreach(@_){  
5:                $s .= tohex($_) . " ";  
6:         }  
7:         chop($s);  
8:         return $s;   
9:  }  
다음과 같이 쓰면 됨.
 my @a = hexarray("A0 A1 A2 FF FE FD");  
 print("@ " . atohexstring(@a) . "\n");  

byte의 array를 string으로 'serialize' 하는 법

1:  sub TESTserializeArray  
2:  {  
3:       my @a = hexarray("A0 A1 A2 FF FE FD");  
4:       my $s = serializeArray(@a);  
5:       print(stohex($s) . "\n");  
6:  }  
7:  sub serializeArray   
8:  {  
9:       my $s = "";  
10:       foreach(@_){  
11:            $s .= pack('C1', $_);       
12:       }  
13:       return $s;  
14:  }  
Perl 에서 binary file 등을 다룰 때는 byte의 연속을 string 으로 보고 작업하므로 이 함수는 유용하다.

string 을 바이트 단위의 hexadecimal 로 얻어내는 Perl 함수

이것은 'serialize' 된 데이터를 hexadecimal 값으로 보는데 유용한 함수이다.
1:  sub TESTstohex  
2:  {  
3:         my $s = "";  
4:         $s .= pack('C1', 255);  
5:         $s .= pack('C1', 254);  
6:         my $h = stohex($s);  
7:         print($h);  
8:  }  
9:  sub stohex  
10:  {  
11:         my $s = $_[0];  
12:         my $result = "";  
13:         my @a = unpack('(C1)*', $s);  
14:         foreach(@a){  
15:                $result .= tohex($_) . " ";  
16:         }  
17:         chop($result);  
18:         return $result;  
19:  }  
4행에서 pack 함수를 쓰지 않으면 255 의 숫자 2, 5, 5가 각자 하나씩의 문자가 되어 들어가버린다.

Perl에서 bit shifting 하기

 my $n = 0b1111;  
 print("$n\n");  
 $n >>= 2;  
 print("$n\n");  
   
 my $m = 0xFF;  
 print("$m\n");  
키워드 : binary, 2진수, 16진수

Object Oriented Programming in Perl

Object Oriented Programming in PERL
Perl Object Oriented Meta-Tutorial
키워드 : OOP, package, separate files

Perl 에서 max min function 쓰는 법

max(), min() 함수를 쓰려면 다음과 같이 먼저 로딩을 해야 한다.
 use List::Util qw[min max];  
 print(min(4,6) . "\n");  
 print(max(1, 2, 3, 4, 5, 6) . "\n");  
 print(max(666) . "\n");  
출처 : Min and max functions in Perl

Sunday, December 30, 2012

hexadecimal 의 array 를 string 으로 얻어내는 Perl 함수

 my @a = hexarray("EF F0 00 0F 01 02");  
 my $s = tohexs(@a);  
 print("$s\n");  
   
 sub tohexs  
 {  
      my $s = "";  
      foreach(@_){  
           $s .= sprintf("%02X ",$_);  
      }  
      chop($s);  
      return $s;  
 }  
   
 sub hexarray   
 {   
      my @s_ = split(/ /, $_[0]);   
      my @a = ();   
      foreach(@s_){   
           push(@a, hex($_));   
      }   
      return @a;      
 }  
tohexs 는 tohexstring 의 줄임.

Perl 에서 array 와 string 사이의 변환

array 를 string 으로 변환해주는 Perl 함수
 sub atos  
 {  
      my $s = join(", ", @_);  
      return $s;  
 }  
다음과 같이 쓰면 array 를 간편히 print 해주기 쉽다.
 my @a = (10, 20, 30, 40);  
 print(atos(@a)."\n");  
string 을 array 로 변환해주는 Perl 함수
 sub stoa  
 {  
      return split(//, $_[0]);  
 }  
Perl에서 string의 문자 하나하나를 다루는 법 참조
키워드 : print array, Perl 에서 array 를 print 해주기

Perl 에서 integer 를 hexadecimal 로 바꿔주는 함수

다음 함수는 decimal 을 hexadecimal 로 변환해준다.
 sub tohex  
 {  
      my $s = sprintf("%X",$_[0]);  
      if(length($s) % 2 == 1){  
           $s = "0" . $s;  
      }  
      return $s;  
 }  
사용법은 다음과 같다.
 print(tohex(254)."\n");  
결과 : 254의 16진수 표기인 FE 가 찍힌다.

8비트 integer 를 두자리 hexadecimal 로 바꿔주는 목적만이라면 다음과 같이 해도 된다.
 sub tohex  
 {  
      sprintf("%02X",$_[0]);  
 }  

hexadecimal string 을 integer array 로 만들어주는 Perl 함수

 sub hexarray
 {  
      my @s_ = split(/ /, $_[0]);  
      my @a = ();  
      foreach(@s_){  
           push(@a, hex($_));  
      }  
      return @a;       
 }  
다음과 같이 사용한다.
 my $s = "FF FE 0A 10";  
 my @a = hexarray($s);  
 print(join(",",@a) . "\n");
결과는 255,254,10,16 와 같이 나온다.
키워드 : 16진수

Saturday, December 29, 2012

Perl 에서 array of arrays 를 다루는 방법

1:  my @aa = ();  
2:  my @a = ("Mega", "Giga", "Tera");  
3:  my @b = ("Centi", "Milli", "Nano");  
4:  push(@aa, \@a);  
5:  push(@aa, \@b);  
6:  foreach(@aa){  
7:         foreach(@$_){  
8:                print();  
9:                print(" ");  
10:         }  
11:         print(" -> First Element is $_->[0]");  
12:         print("\n");  
13:  }  

Perl 에서 array 를 function 의 argument 로 넘기는 방법

1:  my @a = (90, 100, 200, 300, 400);  
2:  printAll(\@a);  
3:    
4:  my $i = 1;  
5:  print("Print one by one : ");  
6:  printAndInc(\@a, \$i);  
7:  printAndInc(\@a, \$i);  
8:  printAndInc(\@a, \$i);  
9:  print("\n");  
10:    
11:  sub printAndInc  
12:  {  
13:       my ($pa, $i) = @_;  
14:       print("$pa->[$$i] ");  
15:       $$i++;  
16:  }  
17:    
18:  sub printAll  
19:  {  
20:       my ($pa) = @_;  
21:       my $result = join(" ", @$pa);  
22:       print("Print all : $result\n");  
23:  }  
13행에서 my (@a, $i) = @_;  와 같이 array 로 받으면 제대로 작동하지 않는다.
키워드 : 함수, parameter

Perl 의 array

perl - array variables

OS X terminal 에서 화면 깨끗이 clear 하기

Command + K 하면 된다.
clear 명령을 쓰면 기존의 명령어는 스크롤해 올라가면 그냥 위쪽에 남아 있다.
키워드 : 터미널

printf 에서 0의 개수를 채워주는 방법

0의 개수를 채워주는 format string의 형태는 %0[숫자]X, %0[숫자]d 처럼 하면 된다. 예를 들어 바이트를 hexadecimal 로 출력할때 0F, 0A 처럼 두자리로 포맷해주려면 다음과 같이 하면 된다.
 sprintf("%02X ",$_);  
키워드 : Perl
레퍼런스 : http://www.cprogramming.com/tutorial/printf-format-strings.html

Perl 에서 decimal 과 hexadecimal 사이의 변환

Decimal → Hexadecimal
 print(tohex(254));
 sub tohex  
 {  
      my $s = sprintf("%X",$_[0]);  
      if(length($s) % 2 == 1){  
           $s = "0" . $s;  
      }  
      return $s;  
 }  
출처 : Perl 에서 integer 를 hexadecimal 로 바꿔주는 함수
Hexadecimal → Decimal
 print(hex("FF"));
레퍼런스 : how to convert decimal to hexadecimal in perl
키워드 : 10진수, 16진수, 십진수

Friday, December 28, 2012

C#으로 MIDI 기능 구현한 프로젝트

Project Description
A synthesizer made in C# that will allow midi functionality using only the compact framework for any .net device: (windows pc, xbox, or phone).
C# Synth Project

Perl 의 true / false 값

if 문에서 쓸 수 있는 boolean 은 없고 C와 똑같이 그냥 1과 0을 쓴다.
integer 중에서는 0 만 false 값이고 나머지는 모두 true 로 취급된다.
 my @a = (-3 .. 3);  
 foreach(@a){  
      if($_){  
           print("$_ is True\n");  
      }else{  
           print("$_ is False\n");  
      }  
 }  
키워드 : boolean

Perl 의 string 과 array 의 length

array length 는 그냥 scalar 값으로 받으면 되고
string length 는 length() 함수 쓰면 된다.
 my @a = (1..5);  
 print "array : scalar(@a)\n";  

 my $a = @a;  
 print "array : $a\n";  

 my $s = "Love me";  
 print "string : " . length($s) . "\n";  
참고로 $#a 는 a 의 last index 값을 나타내는데 여기에 1을 더해서 array count 를 얻어올 수도 있다. 다음 코드는 3을 찍어준다.
 my @a = (1, 3, 5, 7);  
 print($#a);  
 print("\n");  

MIDI file format

Outline of the Standard MIDI File Structure
AIBO MIDI File Format
Standard MIDI format : Meta-Events

The MIDI File Format
The data part of a track chunk contains one or more pairs. The <delta_time> is not optional, but zero is a valid delta-time. delta_time is the number of 'ticks' from the previous event, and is represented as a variable length quantity

The MIDI File Format - about MIDI

Standard MIDI-File Format Spec. 1.1
A crash course on the standard MIDI specification
http://www.piclist.com/tecHREF/io/serial/midi/midifile.html
Note names, MIDI numbers and frequencies

Running Status
The MIDI spec allows for a MIDI message to be sent without its Status byte (ie, just its data bytes are sent) as long as the previous, transmitted message had the same Status. This is referred to as running status. Running status is simply a clever scheme to maximize the efficiency of MIDI transmission (by removing extraneous Status bytes). The basic philosophy of running status is that a device must always remember the last Status byte that it received...

MIDI Channel Prefix meta message
The MIDI channel prefix meta message specifies a MIDI channel so that meta messages that follow are specific to a channel.

MIDI SysEx Tutorial
In an effort to bring System Exclusive (SysEx) messages to the masses, I embarked on a mission to produce this tutorial which will help people plumb the depths of this wonderful and powerful area of MIDI... SysEx is the only means of retrieving data from a synth.

General MIDI Controller Events

MIDI File Format - the Sonic Spot
Standard MIDI files provide a common file format used by most musical software and hardware devices to store song information including the title, track names, and most importantly what instruments to use and the sequence of musical events, such as notes and instrument control information needed to play back the song. This standardization allows one software package to create and save files that can later be loaded and edited by another completely different program, even on a different type of computer. Almost every software music sequencer is capable of loading and saving standard MIDI files.

http://www.blitter.com/~russtopia/MIDI/~jglatt/tech/midifile/ppqn.htm
The MIDI file format's Tempo Meta-Event expresses tempo as "the amount of time (ie, microseconds) per quarter note". For example, if a Tempo Meta-Event contains the 3 bytes of 07 A1 20, then each quarter note should be 0x07A120 (or 500,000) microseconds long.

To convert the Tempo Meta-Event's tempo (ie, the 3 bytes that specify the amount of microseconds per quarter note) to BPM:
BPM = 60,000,000/(tt tt tt)
For example, a tempo of 120 BPM = 07 A1 20 microseconds per quarter note.

Parse and analyze a standard MIDI file

  • File format (Type 0, 1, or 2)
  • Number of tracks
  • Number of distinct channels used
  • Number of distinct voices (instruments) used (look for Program Change messages)
  • Number of ticks per quarter note
  • Shortest two non-zero delta times, reported both in ticks and in microseconds (hint: the timing information you need here is derived from information in two distinct places)
  • Top two longest delta times, both in ticks and in microseconds
  • Minimum non-zero note-on velocity, and its channel and note number
  • Maximum note-on velocity, and its channel and note number
  • Total number of meta-events
MIDI Programming - A Complete Study Part 1 - MIDI File Basics

MIDI Pitch Bend
The two bytes of the pitch bend message form a 14 bit number, 0 to 16383. The value 8192 (sent, LSB first, as 0x00 0x40), is centered, or "no pitch bend." The value 0 (0x00 0x00) means, "bend as low as possible," and, similarly, 16383 (0x7F 0x7F) is to "bend as high as possible." The exact range of the pitch bend is specific to the synthesizer.

Understanding MIDI - MIDI Ports, Channels, and the General MIDI Standard

키워드 : midi file format specification, v_time

Hex Fiend - OS X 용 바이너리 파일 에디터

Hex Fiend, a fast and clever hex editor for Mac OS X
검색어 : os x binary file viewer
키워드 : 바이너리 데이터 에디터, 뷰어

Perl의 regular expression 을 이용해 만든 trim 함수

앞뒤의 whitespace 를 trim 해버리는 코드
 $_ = "  This is my pen. ";  
 print "[" . mytrim() . "]\n";  
 
 sub mytrim {   
      s/^\s+|\s+$//g;  
      return $_;  
 }  
맨 뒤의 g 를 안하면 앞부분만 trim 되고 끝나버린다.

최적화
속도를 높이려면 다음 코드보다는
 s/^\s+|\s+$//g;  
다음 코드를 써서 두 스텝으로 실행하는게 빠르다고 한다.
 s/^\s+//;  
 s/\s+$//;  
그 이유는 ^와 $에 의해 위치가 fixed 되어 있는 regular expression 이 더 효율적으로 동작하기 때문.
출처 : Why is s/^\s+|\s+$//g; so much slower than two separate substitutions?

html의 span tag로 컬러 주는 법 예제

css 사례

키워드 : css, color

Thursday, December 27, 2012

Perl 로 unicode 쓰는 법

레퍼런스 : Why does modern Perl avoid UTF-8 by default?

Perl Regular Expression 코딩예

처음부터 복잡한 regular expression 을 만들려 하지 말고, 단순한 것부터 시작해서 테스트하면서 진화시켜 나간다.
1. 일단 간단히 "my " 라는 단어만 매칭해봄
 $s = "This is my pen. And this is my book. My house is great.";  
 findMine1($s);  
   
 sub findMine1  
 {  
      ($_) = @_;  
      while(/(my )/g){  
           print "[$1]\n";  
      }  
 }  
2. my 뒤에 붙는 alphabet 단어를 매칭해봄
 sub findMine2  
 {  
      ($_) = @_;  
      while(/(my )([a-zA-Z]+)/g){  
           print "[$2]\n";  
      }  
 }  
3. 알파벳 단어 대신 마침표 제외한 모든 문자로 된 단어로 해봄
 sub findMine3  
 {  
      ($_) = @_;  
      while(/(my )([^.]+)/g){  
           print "[$2]\n";  
      }  
 }  
4. 최종형. 공백문자와 마침표를 제외한 모든 단어로 고쳐본 것. my 는 대소문자 안가리게 만듬.
 sub findMine4  
 {  
      ($_) = @_;  
      while(/my\s([^.\s]+)/ig){  
           print "[$1]\n";  
      }  
 }  

Perl 의 shift 함수

array 의 제일 첫 element 를 리턴하고, 그것을 array 에서 제거한다.
쉽게 말하면 Stack의 pop() 과는 반대로 head 를 뽑아내는 함수인 셈이다.
 my @a = (1..5);  
 while (my $elmt = shift(@a)) {  
   print("$elmt ");  
 }  
 print("\n");  
출처 : PERL shift Function

Perl 의 $1, $2, $3... 변수

1:  $_ = "ABC12DE3F4";  
2:  regexTest();  
3:  sub regexTest{  
4:       while (/(\d)/g){  
5:            print("$1 ");  
6:       }  
7:       print("\n");  
8:  }  
결과값은 1 2 3 4 와 같이 나온다.
$1, $2.. 는 최근에 행한 regular expression 에서 매칭된 값들이다.
매칭된 값이란 () 안에 있는 내용으로 위 코드에서는 (\d) 즉 매칭된 숫자열을 말한다.
4행에서 /(\d)/g 로 안쓰고 /\d/g 와 같이 쓰면 매칭은 되지만 $1 값이 세팅이 안되므로 에러가 난다.

 my $s = "98 ba 12 ka";  
   
 if($s =~ /([a-z]+)(\s+(\d+)\s+)/){  
      print "[$1]\n";  
      print "[$2]\n";  
      print "[$3]\n";  
 }  
결과값은 다음과 같이 나온다.
[ba]
[ 12 ]
[12]
즉 순서는 왼쪽에서 오른쪽 / 바깥쪽에서 안쪽이다.

참조 링크 : Perl Regular Expression 코딩예

키워드 : numbers, string, $number variables

Perl Cookbook (O'Reilly)

Perl에서 string의 문자 하나하나를 다루는 법

Perl의 기본 단위는 character가 아니라 string이기 때문에 캐릭터 단위로 다루기 위해서는 string을 분해해야 한다.
캐릭터 하나하나로 분해하는 방법 :
 @array = split(//, $string);  
바이트 단위로 분해하는 방법 :
 @array = unpack("C*", $string);  
루프를 돌려서 한 캐릭터씩 처리하는 법 :
   while (/(.)/g) { # . is never a newline here  
     # do something with $1  
   }  
응용 예) 스트링 내에 어떤 문자가 사용되었는지 알아내는 코드 :
 %seen = ();  
 $string = "an apple a day";  
 foreach $byte (split //, $string) {  
   $seen{$byte}++;  
 }  
 print "unique chars are: ", sort(keys %seen), "\n";  
결과는 unique chars are: adelnpy 와 같이 나온다.
다음과 같이 써도 동일.
 %seen = ();  
 $string = "an apple a day";  
 while ($string =~ /(.)/g) {  
   $seen{$1}++;  
 }  
 print "unique chars are: ", sort(keys %seen), "\n";  
출처 : Perl Cookbook : Processing a String One Character at a Time
키워드 : explode, characters

Perl의 pointer 사용

오브젝트의 포인터를 나타내려면 \를, 포인터가 가리키는 오브젝트를 나타내려면 $를 사용한다.
 my $s = "ABCD";  
 print ("$s\n");  
   
 my $x = \$s;  
 print ("$$x\n");  
다음은 포인터를 이용해서 Array slice 를 얻어본 예.
 my @a = (0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100);  
 my $p = \@a;  
 my @q = @$p[3 .. 6];  
 my @r = @$p[3, 4, 6];  
   
 foreach(@a){  
      print("$_ ");  
 }  
 print("\n");  
   
 foreach(@$p){  
      print("$_ ");  
 }  
 print("\n");  
   
 foreach(@q){  
      print("$_ ");  
 }  
 print("\n");  
   
 foreach(@r){  
      print("$_ ");  
 }  
 print("\n");  
검색어 : google > pointer perl
레퍼런스 :
Advanced Perl Programming - Chapter 1: Data References and Anonymous Storage
References in Perl 5

OS X terminal 색상 및 폰트 조절법

  1. terminal 에서 command + , 로 Preferences 창 띄우고
  2. Settings 탭으로 들어간다.
  3. Text 탭에서 Change... 버튼으로 Font 를 세팅해준다 (디폴트 크기는 너무 작으므로 Courier 14 pt 정도가 적절)
  4. 여기서 좌측을 보면 몇가지 종류의 스킨이 보인다.
  5. Startup 탭으로 들어가면 스킨을 고를 수 있다. On startup, open : New window with settings : 항목에서 선택해주면 된다. Novel 등이 읽기 편하다. 여기서 고른 것은 Settings tab 에서 "Startup" 으로 표시된다.
  6. New windows open with : 와 New tabs open with : 도 same settings, Same Working Directory 로 바꿔주면 편하다.
키워드 : skin, color, 색깔

윈도우에서 한영전환 Shift + Space 로 하는 법

과거의 type 3 처럼 Shift + Space를 쓰는 공식적으로 제공되는 방법은 이제 없다.
굳이 쓰려면 특수한 어플리케이션을 사용하거나 레지스트리를 건드리는 더러운 방법밖에는 없다 (관련링크 : Shift + Space 로 한영전환하기 팁들~ ).

대안
윈도우에서 공식적으로 제공되는 방법으로서는 Ctrl + Shift, Alt + Shift 등을 쓸 수 있는데 적응되면 편하다. 다음과 같이 하면 된다.
  1. 제어판에서 "국가 및 언어" 로 들```어간다.
  2. 키보드 및 언어 탭으로 들어간다.
  3. 추가(D)... 버튼을 누른다.
  4. 목록에서 영어(미국) 의 US 를 체크하고 확인한다.
    이제 "설치된 서비스" 목록에 한국어와 영어(미국)가 있을 것이다.
  5. 고급 키 설정 탭에서 입력언어간 키 시퀀스를 Ctrl+Shift 로 해준다.
이제 Ctrl + Shift 로 한영 전환이 가능하다.
이런 식으로 일본어 등 다른 언어들도 추가하면 된다.
3개 국어 이상을 쓴다면 Ctrl + Shift 를 써서 일관성있게 입력 언어를 변화시킬 수 있다.
키워드 : 타입3, 윈도우7, 한영키

윈도우 시스템 복원 관련 자료

Dell DataSafe Local Backup 유틸리티를 이용한 시스템 복구 디스크 생성하는 방법
이 문서는 시스템 복구 디스크를 만드는 방법에 대해 설명합니다.
  1. 시작 > 모든 프로그램 > Dell DataSafe Local Backup 을 차례로 클릭하고 Dell DataSafe Local Backup 을 클릭합니다.
  2. 복구 디스크 생성(Create your Recovery Discs)을 클릭합니다.
  3. 지금 내 복구 디스크 생성(Create My Recovery Disc(s) Now)을 클릭하고 다음 버튼을 눌러줍니다.
  4. 공DVD 또는 USB메모리를 매체로 선택할 수 있음. 미디어 선택 후 지시대로 진행하면 됨.
Dell DataSafe Local Backup 유틸리티를 이용하여 Dell 컴퓨터를 출하 시 설치 상태로 복원
  1. 컴퓨터를 켜고, Dell 로고가 나타났다가 사라지면 고급 부팅 옵션 메뉴가 나타날 때까지 0.5초간격으로 키를 여러 번 누릅니다.
  2. 고급 부팅 옵션에서 화살표 키를 사용하여 컴퓨터 복구를 강조 표시하고 ENTER 키를 누릅니다.
  3. 시스템 복구 옵션에서 키보드 입력 방법은 Microsoft 한글 입력기를 선택 후 다음(N) > 을 누릅니다. 
  4. 다음(N) > 을 클릭 후 컴퓨터의 관리자 계정에 로그인합니다. 관리자 계정은 컴퓨터를 처음 시작했을 때 생성된 계정입니다.
  5. 복구 도구를 선택하십시오 항목에서 Dell DataSafe 복원 및 긴급 백업을 클릭합니다. 
  6. 다른 시스템 백업 및 추가옵션 선택 항목을 선택한 후 다음 > 을 누릅니다. 
  7. 내 컴퓨터 복원 항목을 선택한 후 다음 > 을 누릅니다. 
  8. 출하시 이미지 201*-**-** ** **:**:** 항목을 선택한 후 다음 > 을 누릅니다. 
  9. 새 파일이나 변경된 파일을 보존하지 않고 복원 항목을 선택한 후 다음 > 을 누릅니다. 
  10. 예, 계속합니다항목을 선택한 후 다음 > 을 누릅니다.
    컴퓨터 복구 시간은 약 20~30분 정도 소요됩니다. 참고로 컴퓨터 사양에 따라 시간이 더 걸릴 수도 있습니다.
  11. 공장 초기화가 완료되었습니다. 다시시작 > 을 눌르면 시스템이 자동으로 다시 부팅되며 윈도우 초기 설정 화면이 나타나며 화면의 설정안내에 따라 마무리 작업을 해주면 됩니다.
기타 : Dell System 복원 CD(SRCD)를 사용하는 방법 - KB Article - 128289
Dell™ 소프트웨어 복구 CD(SRCD)의 설치 절차
1. 외부 주변 장치(프린터, 스캐너 및 카메라 등)를 모두 분리한 후 메모리를 포함하여 컴퓨터에 출하 시 설치되지 않은 모든 내부 주변 장치를 분리합니다...

Microsoft® Windows® 시스템 복원 사용
Windows 운영 체제는 하드웨어, 소프트웨어 또는 기타 시스템 설정에 대한 변경 사항으로 인해 컴퓨터 작동 상태에 이상이 발생한 경우 데이터 파일에 영향을 주지 않고 컴퓨터를 이전 상태로 되돌릴 수 있는 시스템 복원 옵션을 제공합니다. 시스템이 복원을 사용하여 컴퓨터에 대해 수행한 모든 변경사항은 전부 되돌릴 수 있습니다.
  1. 시작 을 클릭합니다.
  2. 검색 시작 상자에 시스템 복원을 입력하고 키를 누릅니다.주: 사용자 계정 컨트롤 창이 나타날 수 있습니다. 컴퓨터 관리자인 경우 계속을 클릭하고 관리자가 아닌 경우 관리자에게 문의하여 원하는 작업을 계속합니다.
  3. 다음을 클릭하고 화면의 나머지 지시사항을 따릅니다.
Dell™ PC 복원 및 Dell 출하 시 이미지 복원 사용
Dell 출하 시 이미지 복원 (Windows Vista) 또는 Dell PC 복원 (Windows XP)을 운영 체제를 복원하는 마지막 방법으로만 사용하십시오.
이러한 옵션은 컴퓨터를 구입했을 때의 작동 상태로 하드 드라이브를 복원합니다. 컴퓨터를 받은 후에 추가한 모든 프로그램 또는 파일(데이터 파일 포함)은 하드 드라이브에서 영구적으로 삭제됩니다. 데이터 파일 에는 문서, 스프레드시트, 전자 우편 메시지, 디지털 사진, 음악 파일 등이 포함됩니다. 가능하면 PC 복원 또는 출하 시 이미지 복원을 사용하기 전에 모든 데이터를 백업하십시오.
  1. 컴퓨터를 켜십시오. Dell 로고가 나타나면 키를 여러 번 눌러 Vista 고급 부팅 옵션 창에 액세스합니다.
  2. 컴퓨터 복구를 선택합니다.
    시스템 복구 옵션 창이 나타납니다.
  3. 키보드 레이아웃을 선택하고 다음을 클릭합니다.
  4. 복구 옵션에 액세스하려면 로컬 사용자로 로그온합니다. 명령 프롬프트에 액세스하려면 사용자 이름 필드에 administrator를 입력한 다음 OK(확인)를 클릭합니다.
  5. Dell Factory Image Restore (Dell 출하 시 이미지 복원)를 클릭합니다.
    주: 구성에 따라 Dell Factory Tools (Dell 출하 시 도구)를 선택한 다음 Dell Factory Image Restore (Dell 출하 시 이미지 복원)를 선택해야 할 수 있습니다.
    Dell Factory Image Restore (Dell 출하 시 이미지 복원) 시작 화면이 나타납니다.
  6. Next (다음)를 클릭합니다.
    Confirm Data Deletion (데이터 삭제 확인) 화면이 나타납니다.
    주의사항: 출하 시 이미지 복원을 계속 실행하지 않으려면 Cancel (취소)을 클릭합니다.
  7. 계속 하드 드라이브를 재포맷하고 시스템 소프트웨어를 초기 설정 상태로 복원함을 확인하는 확인란을 클릭한 후 Next (다음)를 클릭합니다.
    복원 프로세스가 시작되며 이 프로세스를 완료하는 데 5분 이상 소요됩니다. 운영 체제 및 초기 설정 응용프로그램이 초기 설정 상태로 복원된 경우 메시지가 나타납니다.
  8. Finish (마침)를 클릭하여 시스템을 재부팅합니다.
키워드 : 델컴퓨터 시스템 복구 디스크 윈도우7 비스타
레퍼런스 :
Dell™ PC 복원 및 Dell 출하 시 이미지 복원 사용
Dell DataSafe Local Backup 유틸리티를 이용한 시스템 복구 디스크 생성하는 방법

Perl에서 포인터 사용하기

Advanced Perl Programming: Sample Chapter - Chapter 1: Data References and Anonymous Storage
검색어 : Perl Pointer

Wednesday, December 26, 2012

Perl 의 pack 과 unpack 함수

pack과 unpack 은 데이터를 serialize 하고 그것을 푸는 기능으로, 파일에 읽고 쓰는 작업 등에 쓰기 좋다. 다음과 같은 포맷으로 쓴다.
 LIST = pack TEMPLATE, EXPR
 LIST = unpack TEMPLATE, EXPR  
TEMPLATE 는 다음 형식을 가진다.
 [template characters][repeat number]
template character 에는 A, B, C 등 여러가지가 있는데 예를 들어 C4 이라는 것은 byte 4개를 뜻하고 A10 이라는 것은 ASCII 스트링을 뜻한다. repeat number 를 딱히 정하지 않고 * 로 쓸수도 있다. template character 에는 다음과 같은 것들이 있다.
 A string with arbitrary binary data, will be null padded
 A  A text (ASCII) string, will be space padded
 b  A bit string (ascending bit order inside each byte, like vec()) 
 B  A bit string (descending bit order inside each byte)
 c  A signed char (8-bit) value
 C  An unsigned char (octet) value
 d  A double-precision float in the native format
 f  A single-precision float in the native format
 h  A hex string (low nybble first)
 H  A hex string (high nybble first)
 i  A signed integer value
 I  A unsigned integer value
 l  A signed long (32-bit) value
 L  An unsigned long value
 n  An unsigned short (16-bit) in "network" (big-endian) order
 N  An unsigned long (32-bit) in "network" (big-endian) order
 s  A signed short (16-bit) value
 S  An unsigned short value
 U  A Unicode character number
 v  An unsigned short (16-bit) in "VAX" (little-endian) order
 V  An unsigned long (32-bit) in "VAX" (little-endian) order
 x  A null byte
 X  Back up a byte
사용예 :
다음과 같이 pack 하고
    open (OUTFILE, ">$outfile") or die "error : $!";   
    binmode (OUTFILE);   
       
    $buffer .= pack 'B8', "11110000"; # 240 = 128 + 64 + 32 + 16   
    $buffer .= pack 'B8', "11110001"; # 241   
    $buffer .= pack 'B8', "11110010"; # 242   
    $buffer .= pack 'B8', "11110011"; # 243   
    $buffer .= pack 'C1', 0;   
       
    $buffer .= pack 'C1', 200; # 200   
    $buffer .= pack 'H4', "FEFF"; # 254, 255   
    $buffer .= pack 'C1', 0;   
     
    $buffer .= pack 'A2', "ab";

    print OUTFILE $buffer;   
    close OUTFILE;   
다음과 같이 unpack 한다.
    open (INFILE, "$infile") or die "error : $!";   
    binmode (INFILE);   
       
    my ($buf, $data, $n);   
    for (; ($n = read INFILE, $data, 65536) != 0; $buf .= $data){   
       print "Reading $n bytes from file: $infile\n";   
    }   
    close(INFILE);   
     
    my @buffer;   
    @buffer = unpack('(C1)*', $buf);   
    foreach (@buffer){   
       print();   
       print "\n";   
    }   
Read 한 결과는 다음과 같다.
 Read mode.  
 Reading 11 bytes from file: mytest.bin  
 240  
 241  
 242  
 243  
 0  
 200  
 254  
 255  
 0  
 97  
 98  
 buffer size is 11.  
샘플코드 : Perl 에서 Binary File 읽고 쓰기 샘플 코드
레퍼런스 :
Perl unpack Function
perlpacktut - tutorial on pack and unpack
pack
unpack

Perl 에서 Binary File 읽고 쓰기 샘플 코드

USAGE :
 $ ./test.pl -w  
 $ ./test.pl -r  
Code :

#!/usr/bin/perl -w
 use strict;
 use warnings;

 main("mytest.bin");  
   
 sub main  
 {  
      print("--------------------------------------------------\n");  
      my ($mode) = @ARGV;  
      my $numArgv = @ARGV;  
      if($numArgv == 0){  
           print("arguments : -r to read and -w to write\n");  
           exit(0);  
      }  
      else{  
           if($mode =~ /^-w$/i){  
                writeBinFile(@_);  
           }  
           elsif($mode =~ /^-r$/i){  
                readBinFile(@_);  
           }  
      }  
      exit 0;  
 }  
   
 sub writeBinFile  
 {  
      print("Write mode.\n");  
   
      my (($outfile), $buffer) = (@_, undef);  
      my ($num_bytes, $errmsg) = (1024, "Couldn't write to $outfile");  
        
      open (OUTFILE, ">$outfile") or die "$errmsg : $!";  
      binmode (OUTFILE);  
        
      $buffer .= pack 'B8', "11110000"; # 240 = 128 + 64 + 32 + 16  
      $buffer .= pack 'B8', "11110001"; # 241  
      $buffer .= pack 'B8', "11110010"; # 242  
      $buffer .= pack 'B8', "11110011"; # 243  
      $buffer .= pack 'C1', 0;  
        
      $buffer .= pack 'C1', 200; # 200  
      $buffer .= pack 'H4', "FEFF"; # 254, 255  
      $buffer .= pack 'C1', 0;  
   
      $buffer .= pack 'A2', "ab";  
      print OUTFILE $buffer;  
      close OUTFILE;  
        
      print("Write success.\n");  
 }  
   
 sub readBinFile  
 {  
      print("Read mode.\n");  
        
      my (($infile), $buffer) = (@_, undef);  
      my ($num_bytes, $errmsg) = (1024, "Couldn't read from $infile.");  
        
      open (INFILE, "$infile") or die "$errmsg : $!";  
      binmode (INFILE);  
        
      my ($buf, $data, $n);  
      for (; ($n = read INFILE, $data, 65536) != 0; $buf .= $data){  
           print "Reading $n bytes from file: $infile\n";  
      }  
      close(INFILE);  
   
      my @buffer;  
      @buffer = unpack('(C1)*', $buf);  
      foreach (@buffer){  
           print();  
           print "\n";  
      }  
      my $sizeBuffer = @buffer;       
      print "buffer size is $sizeBuffer.\n";  
 }  
Result :
 Read mode.  
 Reading 11 bytes from file: mytest.bin  
 240  
 241  
 242  
 243  
 0  
 200  
 254  
 255  
 0  
 97  
 98  
 buffer size is 11.  
키워드 : Read, Write, 바이너리 파일, 이진파일, binmode

Perl 에서 NULL value assign 하기

인용 : There's no NULL in perl. Use undef when you mean "no value". Also, variables are undefined by default. So my $var is equivalent to my $var = undef.
레퍼런스 : http://stackoverflow.com/questions/3224312/how-can-variables-be-set-to-null-under-the-strict-pragma

Perl 의 ord() and chr() function

 my $n = ord "a";  # 97  
 my $c = chr 97;  # 'a'  
 print "[$c] = $n\n";  
ord 는 주어진 문자의 애스키 코드를 얻어냄.
chr 는 주어진 코드 번호에 대한 문자를 얻어냄.
키워드 : ascii code

ASCII code table

Control characters : 0-31, 127(DEL)
Line Feed : 10 (0x0A)
Carriage Return : 13 (0x0D)
NULL : 0

Printable characters : 32-126
space : 32 (0x20)
0-9 : 48-57 (0x30-0x39)
A-Z : 65-90 (0x41~0x5A)
a-z : 97-122 (0x61~0x7A)

링크 : http://www.theasciicode.com.ar/
키워드 : 아스키 코드 테이블, 애스키

Perl 에서 multiline comment 다는 법

다음과 같이 하면 된다.
 =Comment  
 코드  
 =cut  
위쪽에는 아무거나 쓸 수 있지만 끝은 항상 =cut 으로 끝나야 한다.
 =You can write anything here  
 코드  
 =cut  
아무것도 안써주면 안된다.
 =  
 코드  
 =cut  
키워드 : multiple lines, 멀티라인, 여러줄, 주석, 코멘트

Perl 에서 binary file 읽고 쓰기

 #!/usr/bin/perl -w  
 #Source: http://perlmeme.org/faqs/system/binmode.html  
 use strict;  
 use warnings;  
   
 my $buffer;  
 my $num_bytes = 1024;  
 my $infile = "test.png";  
 my $outfile = "test2.png";  
   
 open (INFILE, $infile) or die "Couldn't open $infile for reading: $!";  
 open (OUTFILE, ">$outfile") or die "Couldn't open $outfile for writing: $!";  
 binmode(INFILE);  
 binmode (OUTFILE);  
   
 while (read(INFILE, $buffer, $num_bytes)) {  
      print OUTFILE $buffer;  
 }  
 close INFILE;  
 close OUTFILE;  
 exit 0;  
How do I write binary files on a non-Unix OS?
키워드 : binmode, read, write

Perl 의 file open 함수

http://perldoc.perl.org/functions/open.html
→ mode에 대해 잘 나와 있음.
예)
 open(my $fh, "<", "input.txt") or die "cannot open < input.txt: $!";  
 open(my $fh, ">", "output.txt") or die "cannot open > output.txt: $!";  
 open(my $fh, "<:encoding(UTF-8)", "filename") || die "can't open UTF-8 encoded filename: $!";  
 open(my $tmp, "+>", undef) or die ...  
 open($fh, ">", \$variable) || ..  

Perl 에서 텍스트 파일에 쓰기

 open (MYFILE, '>>test.txt');  
 print MYFILE "Hey, This is me.\nHahaha";  
 close (MYFILE);  
키워드 : writing, write, text file

Perl 의 join function

join 함수는 다음과 같이 쓴다.
일일이 dot operator 로 연결하는 것보다 훨씬 짧게 코딩 가능.
 my @names = qw/Apple Melon Orange/;  
 my $names = join " and ", @names;  
 print($names);   
 print("\n");  
결과 : Apple and Melon and Orange
Perl join Function

Perl의 qw 함수

다음 둘은 동일하다.
 my @names = ('Apple', 'Melon', 'Orange');  
 my @names = qw(Apple Melon Orange);  
qw 는 whitespace 를 delimiter 로 삼아서 단어들을 추출한다.
() 가 아니라 / /, { }, ' ' 등으로 둘러싸도 된다. 특히 다음과 같이 많이 쓴다.
 my @names = qw/Apple Melon Orange/;  
다음 같이 써도 잘된다.
 my @names = qw:Apple Melon Orange:;  
Using the Perl qw() function

Tuesday, December 25, 2012

Perl 의 loop 에서 continue 및 break 하는 법

continue 에 해당하는 것은 next 이고
break 에 해당하는 것은 last 이다.

다음 코드는
 for $i ( 0 .. 100 )   
 {  
      next if($i % 2 == 0);  
      last if($i > 10);  
      print($i);   
      print(" ");  
 }  
 print "\n";  

다음과 동일하다.
 for $i ( 0 .. 100 )   
 {  
      if($i % 2 == 0){  
           next;  
      }  
      if($i > 10){  
           last;  
      }  
      print($i);   
      print(" ");  
 }  
 print "\n";  

참고로 Perl 에서 if 문은 statement의 뒤쪽에 올 수 있다.
 for $i ( 0 .. 10 )   
 {  
      print($i . " is even. ") if($i % 2 == 0);  
 }  
 print "\n";  

키워드 : for, while
레퍼런스 : 
Perl next operator - for loop and if statement examples
07 - Control Statements

next 문

다음 코드에서 comment 를 해제하면 공백인 라인은 빼고 프린트해준다.
 $MYFILE = "/Users/testText.txt";  
 open(MYFILE);  
 while (<MYFILE>) {  
      chomp();  
 #     next if(/^$/);  
      print();  
      print("/");  
 }  
 close(MYFILE);  

Perl 의 생략 기능

 @ARGV = ("1.txt", "2.txt");  
 while (<>) {  
   print();  
 }  
위 코드의 while 문에는 두가지가 생략되어 있다. 우선 읽어오는 파일이 무엇인지 파일 핸들러가 무엇인지 생략되어 있고 그것을 어디로 읽어오는지 그 변수도 생략되어 있다. Diamond Operator 안쪽에 파일 핸들러가 생략되어 있으면 그것은 디폴트로 @ARGV 이고 만일 @ARGV 가 없으면 @STDIN 이 된다.

즉 while(<>) 은 while($_ = <@ARGV>) 또는 while($_ = <@STDIN>) 의 생략형이다.

레퍼런스 : 09 - Using Files

Perl 에서 File open() 함수 쓰는 몇가지 방법

다음 중 어떤 방식으로 써도 상관 없다. 둘은 똑같은 코드이다.
 $MYFILE = "/Users/hur/new/Work cur/scripts/MyPerlScripts/testText.txt";  
 open(MYFILE);  
 while (<MYFILE>) {  
      print();  
 }  
 close(MYFILE);  
 $MYFILE = "/Users/hur/new/Work cur/scripts/MyPerlScripts/testText.txt";  
 open(F, $MYFILE);  
 while (<F>) {  
      print();  
 }  
 close(MYFILE);  
전자의 경우 $MYFILE 는 파일명 스트링이고 MYFILE 은 file handler 로 서로 완전히 다른 존재이다.

Perl 의 File 테스트 함수들 (File Test Operators)

-e File exists. -z File has zero size (is empty). -s File has nonzero size (returns size in bytes).
-f File is a plain file. -d File is a directory. -l File is a symbolic link. -p File is a named pipe (FIFO), or Filehandle is a pipe. -S File is a socket. -b File is a block special file. -c File is a character special file. -t Filehandle is opened to a tty.
-u File has setuid bit set. -g File has setgid bit set. -k File has sticky bit set.
-T File is an ASCII text file (heuristic guess). -B File is a "binary" file (opposite of -T).
-M Script start time minus file modification time, in days. -A Same for access time. -C Same for inode change time (Unix, may differ for other platforms)
레퍼런스 : 
What does if( -f ) in perl do?
09 - Using Files

Perl 의 Split 함수

Split 함수의 기본적인 사용
$s = "Happy:Lucky:Go";
@a = split(/:/, $s);   # ("Happy", "Lucky", "Go");

코드를 짧게 써보면
$_ = "Happy:Lucky:Go";
@a = split(/:/);   # ("Happy", "Lucky", "Go");

Regular expression 을 이용해 delimiter 를 지정할수 있다.
$_ = "Happy:Lucky:::Go";
@s = split(/:+/);

Split 함수 사용예
Paragraph 를 sentence 단위로 나눠보면
@sentence = split(/\./, $paragraph)

Sentence 를 word 단위로 나눠보면
@words = split(/ /, $sentence);

Word 를 character 단위로 나눠보면
@chars = split(//, $word);

키워드 : string functions
레퍼런스 :
http://www.comp.leeds.ac.uk/Perl/split.html

Perl에서 File Read 하기

File 열기
open(F, $filename);
과 같이 실행하면 파일을 연다. F 가 파일 핸들러가 된다.

The Diamond Operator
이제 파일 핸들러를 이용해 파일의 내용을 불러와야 되는데 이때 쓰이는 것이 diamond operator이다. File Hander 를 F 라고 할때 라고 쓰면 파일 내용을 한 라인씩 불러온다. 여기서 '라인'이란 'input record separator' 에 저장된 스트링으로 나뉜 단위를 말한다. input record separator 는 $/ 라는 predefined 변수에 저장된 값이며 디폴트 값은 newline character이다.

예)
@lines = <F>; # 파일 전체 내용을 array 에 불러온다.
$line = <F>; # 파일을 한줄씩 불러온다.
이처럼 Array 로 받으면 파일 전체를 읽어오고 scalar 값으로 받으면 한줄씩 불러오는 차이가 있다.

File 닫기
읽고 나면 파일을 닫는다.
close(F);

특수한 파일 핸들러 STDIN (standard input)
사용자 입력은 개념적으로 File handler 와 동일하다.
print "What is your name?";
$name = <STDIN>;

Diamond Operator 에 파일 핸들이 안주어지는 경우
생략되면 우선 @ARGV 를 찾고, arguments 가 안주어졌으면 STDIN 에서 받는다.
 while (<>) {  
   print();  
 }  

Binary File 읽는 법 (여기 나온 코드 이용한 것)
 use strict;  
 use warnings;   
 my $file = "/Users/hur/new/Work cur/scripts/MyPerlScripts/test12bytes.bin";  
 my $errmsg = "\nUnable to open $file\n";  
   
 die $errmsg unless(open FILE, $file);  
 binmode(FILE);  
   
 # Get rid of the line separator. This allows us to read everything in one go.  
 undef $/;  
   
 # Read the entire file. If you don't want to read all of it at once, you need the read() subroutine.
 my $contents = <FILE>;  
   
 print "Read " . length($contents) . " bytes\n";  
 close FILE;  

Text File 읽기 (전체 파일 내용을 하나의 string 으로 가져옴)
 sub LoadTextFile  
 {  
      my $filepath = shift;  
      open(F, $filepath);   
      my @lines_ = <F>;   
      close(F);   
      my $result;  
      my @lines;  
      foreach my $line (@lines_){   
           $result .= $line;  
      }  
      return $result;  
 }  

Text File 읽기 (라인별로 array로 가져오기. LF, CR, CRLF 세가지 모두 다룰 수 있게 한 것)
 use strict;  
 use warnings;  
 main();  
 sub main  
 {  
      if(scalar(@ARGV) == 0){ exit(0); }  
      my $filepath = $ARGV[0];  

      open(F, $filepath);  
      my @lines_ = <F>;  
      close(F);  

      my @lines;  
      foreach my $line (@lines_){  
           $line = trimNewlines($line);  
           my @a = split(/\r/, $line);   
           foreach(@a){  
                push(@lines, $_);  
           }  
      }  
      printDS(\@lines);  
 }  
 sub trimNewlines  
 {  
      my $string = shift;  
      $string =~ s/[\r|\n]+$//;  
      return $string;  
 }  
 sub printDS  
 {  
      my $ds = shift;  
      use Data::Dumper;   
      print Dumper @$ds;  
      print "\n";  
 }  

Perl의 File 관련 함수들
File Functions
File Test Operators

레퍼런스 :
File handling (http://www.comp.leeds.ac.uk/Perl/filehandling.html)
The Diamond Operator
Perl 5 by example by David Medinets 09 - Using Files
Perl File Open: Creating, Reading and Writing to Files in Perl
perlpacktut - tutorial on pack and unpack

키워드 : Read / Write

시스템에 Perl이 깔려 있나 확인하는 법

$ perl -v
실행하면 버전 정보 나옴

Perl 5 by example by David Medinets

Perl 5 by example by David Medinets 09 - Using Files

Perl 의 my command

local variable 정의시에 쓴다. 보통 다른 스크립트 언어의 local 이라는 키워드와 같다고 생각하면 된다.
예) 다음과 같이 쓰면 for 블럭 내의 print 문은 실행이 되지만 바깥쪽의 print 문은 실행이 안된다.
 for (1..5) {  
   my $s = "hello\n"  
   print $s;  
 }  
 print $s;  
My command in perl? I can't for the life of me figure out what this command means...

Perl Regular Expressions 레퍼런스

  • A Regex Introduction - Tutorial. Covers basic syntax, tricks and traps. → 링크 죽은듯
  • CPAN - Collection of regex modules. Includes documentation and download.
  • Equinoxbase - Online application. Converts Perl 5 regexps for Perl 6.
  • How Regexes Work - Collection of Perl regex resources. Includes tutorial, slideshow, class summary, code modules, PDF e-book.
  • MakeRegex - Perl module that creates regular expressions from word lists. Includes tester, instructions and download.
  • Perl Regular Expression Quick Reference - One-page cheat sheet. Contains tables of syntax elements such as character classes, quantifiers and modifiers. [PDF]
  • Perl Regular Expressions - Tutorial. Covers matching, replacing and sample problems such as matching a file path's double dots.
  • Perl Regular Expressions by Example - Basic introduction to Perl regex. Includes examples and partial syntax reference.
  • Perl.org - Regex resources on the official Perl site. Includes manual pages, tutorials and FAQs.
  • Perlfect - Online regex tester. Displays matches in bold.
출처 : http://www.dmoz.org/Computers/Programming/Languages/Regular_Expressions/Perl/

Perl의 Regular Expression에 쓰이는 special characters

.  # Any single character except a newline
^  # The beginning of the line or string
$  # The end of the line or string
*  # Zero or more of the last character
+  # One or more of the last character
?  # Zero or one of the last character

t.e   # the, tae 같은 것들. te 나 take 같은 건 해당되지 않음 (.는 한글자이기 때문)
^f   # f가 라인 첫머리에 오는 것. fate 같은 것들
^fine  # fine 이 라인 첫머리에 오는 것. "fine, thank you. and you?" 같은 것들
e$   # e가 라인 맨끝에 오는 것. tone, rhode 같은 것들
ade$  # ade가 라인 맨끝에 오는 것. ade, made 같은 것들
old*  # ol 뒤에 d가 0개 이상 오는 것. ol, old, oldd, olddd 같은 것들
.*   # 개행이 없는 모든 스트링 (왜냐하면 .는 newline 캐릭터가 아닌 모든 글자이고 *는 0개 이상이므로)
^$   # 빈 라인. 시작(^) 뒤에 바로 끝($)이 오므로.

[aeiou]   # 영소문자 모음들.
[^aeiou]   # 영소문자 모음이 아닌 것들
[a-z]     # 영소문자. a~z 까지의 아무 글자
[^a-z]    # 영소문자가 아닌 글자
[a-zA-Z]   # 아무 알파벳 글자
[a-z]+    # 영소문자 한개 이상으로 이루어진 스트링

money|fame   # money 또는 fame
(mega|giga)death # megadeath 또는 gigadeath
(la)+      # la 또는 lala 또는 lalala...

\n  # 개행문자. A newline
\t  # 탭. A tab
\w  # Any alphanumeric (word) character. [a-zA-Z0-9_] 와 같음.
\W  # Any non-word character. [^a-zA-Z0-9_] 와 같음.
\d  # 숫자. [0-9] 과 동일
\D  # 숫자가 아닌 것. [^0-9] 과 동일.
\s  # 공백문자. Any whitespace character: space, tab, newline, etc
\S  # 공백문자가 아닌것. Any non-whitespace character
\b  # A word boundary, outside [] only
\B  # No word boundary

\|  # Vertical bar
\[  # An open square bracket
\)  # A closing parenthesis
\*  # An asterisk
\^  # A carat symbol
\/  # A slash
\\  # A backslash

활용예제
[01]       # "0" 또는 "1"
\/0        # "/0"
\/\s0       # "/ 0" 같은 것들. 중간의 스페이스는 tab 등의 다른 whitespace 가 될 수 있음
\/\s*0       # "/ 0" 처럼 whitespace 가 많이 올 수 있고 "/0" 처럼 없을 수도 있음
\/\s*0\.0*     # "/ 0.0", "/ 0.0000", "/0." 같은 것들.

레퍼런스 : String matching

Perl의 Predefined Names

Predefined Names
$_, $! 등 설명.

$_
$_ 는 쉽게 말해 자연어의 '그거' 와 비슷하다. 예를 들면 다음 코드는
 while ($inputLine = <STDIN>) {  
   print($inputLine);  
 }  
다음과 같이 쓸 수 있다.
 while (<STDIN>) {  
   print();  
 }  
그 이유는 if 문의 내부 혹은 print 문의 내부에 argument 를 지정해주지 않으면 그것은 디폴트 파라메터인 $_ 가 되기 때문이다. 즉 위 코드는 아래 코드와 동일.
 while ($_ = <STDIN>) {  
   print($_);  
 }  
이는 단지 syntactic sugar 라기보다는 Perl 의 귀차니즘 철학을 잘 나타내주는 핵심기능으로 매우 자주 쓰인다.

$_의 사용예
 $FILE = "/Users/hur/new/Work cur/scripts/MyPerlScripts/testText.txt";  
 open(FILE);  
 foreach (<FILE>) {  
      chomp();  
      print();  
      print(" ");  
 }  
 close(FILE);  
위 코드에서 foreach 의 대상이 되는 변수도, chomp() 의 대상이 되는 변수도, print() 의 대상이 되는 변수도 전혀 지정되지 않았다. 이런 경우는 '그거' 즉 $_ 를 대상으로 삼는다. 즉 위 코드는 아래의 것과 동일하다.
 $FILE = "/Users/hur/new/Work cur/scripts/MyPerlScripts/testText.txt";  
 open(FILE);  
 foreach $_(<FILE>) {  
      chomp($_);  
      print($_);  
      print(" ");  
 }  
 close(FILE);  

$/
이것은 input record separator 라고 하여 Diamond operator 가 읽어오는 단위를 결정해준다.
디폴트값은 newline 이다. 즉 $/ 가 디폴트값인 newline 으로 되어 있으면 $line = <FILE> 을 실행할 때 newline 단위로 한줄씩 읽어온다.

$! 
$! 는 최근의 error number이다.
open (F, $filepath) or die "can not open file. Error number : $!";  와 같이 씀.

기타
$& 는 속도를 떨어뜨리므로 쓰지 않는게 좋다고 함 (출처)

Perl Regular Expressions

코딩예
Perl Regular Expressions by Example → 가장 알기 쉬운 설명. 처음 보기에 좋음
Steve Litt's Perls of Wisdom: Perl Regular Expressions → 매우 설명이 잘돼 있음
String matching, Regular Expressions → $_ 에 대한 설명이 있음

A라는 regular expression 이 있을때 스트링 $s 가 매치하는지 비교하려면
if($s =~ /A/) 와 같이 쓴다. 매치하지 않는지 비교하려면 if($s !~ /A/) 와 같이 쓴다.

m 은 주어진 regular expression 에 match 되는 것을 찾을 때 쓰이고
s 는 주어진 regular expression 에 match 되는 것을 바꿔치기 (substitution) 할때 쓰인다.
$string =~ m/Bill Clinton/;               #return true if var $string contains the name of the president
$string =~ s/Bill Clinton/Al Gore/;  #replace the president with the vice president

다음 둘은 같다.
$string =~ m/Bill Clinton/;            #return true if var $string contains the name of the president
$string =~ /Bill Clinton/;               #same result as previous statement

^는 라인의 처음을 의미한다.
$string =~ m/^Bill Clinton/;            #true only when "Bill Clinton" is the first text in the string

$는 라인의 끝을 의미한다.
$string =~ m/Bill Clinton$/;            #true only when "Bill Clinton" is the last text in the string

i는 case insensitive한 오퍼레이션을 의미.
$string =~ m/Bill Clinton/i;            #true when $string contains "Bill Clinton" or BilL ClInToN"

$_ 는 "default parameter" 로, 코드를 짧게 쓸수 있게 해준다.
다음 둘은 같은 코드이다.
 $s = "a lewd sentence about sex";  
 if ($s =~ /sex/)  
 {  
      print "$s -> This is for adults!\n";  
 }  
 $_ = "a lewd sentence about sex";  
 if (/sex/)  
 {  
      print "$_ -> This is for adults!\n";  
 }  
예제) $1 와 modifier g
$1는 매칭된 패턴에 걸린 첫 결과값이다. 처음 결과값만이 아니라 스트링 전체를 다 검색하려면 modifier g (global search)를 사용하면 된다 (좌에서 우로 스트링 전체를 다 검색).
 $mystring = "[2004/04/13] The date of this article.";  
 while($mystring =~ m/(\d+)/g) {  
      print "Found number $1.";  
 }  
코드 출처 : Perl Regular Expressions by Example
다음 코드의 결과는 "A B C D E F "가 프린트되지만 modifier g 를 빼고 실행하면 A만 무한히 프린트된다.
 my $_ = "ABCDEF";  
 charByCharMethod();  
 sub charByCharMethod{  
      while (/(.)/g) { # . is never a newline here   
           print("$1 ");  
      }  
      print("\n");  
 }  

Regular expression 의 중요성
Without regular expressions, Perl would be a fast development environment. Probably a little faster than VB for console apps. With the addition of regular expressions, Perl exceeds other RAD environments five to twenty-fold in the hands of an experienced practitioner, on console apps whose problem domains include parsing (and that's a heck of a lot of them)...

키워드 : match, =~ 심볼
관련링크 :
Perl Regular Expressions by Example
Perl의 Regular Expression에 쓰이는 special characters
Perl의 Predefined Names ... $_ 등
Regular expressions in Perl