Showing posts with label Perl. Show all posts
Showing posts with label Perl. Show all posts

Thursday, March 24, 2016

Perl 에서 EUC-KR 로 인코딩 된 텍스트 파일 유니코드로 로딩하는 법

다음과 같이 하면 된다.

my $text = `iconv -c -f euc-kr -t utf-8 \"$filepath\"`;

키워드 : text file, utf-8, load, unicode, euckr, euc-kr, encoding, 한글

Perl regular expression 에서 Multiple Lines 매칭하는 법

/s 와 /m 옵션을 활용하면 된다.

/s
. 는 원래 newline 을 매치하지는 않으나 /s 옵션을 쓰면 . 가 \r 이나 \n 도 매치할수 있게 해준다.

/m
^ 과 $ 는 원래 매치하는 텍스트의 맨 처음과 끝이지만 /m 옵션을 쓰면 ^ 과 $ 가 중간의 newline character 로 개행된 바로 다음부터 매치되도록 해준다.

키워드 : regular expression, multiline, match, 개행문자, 개행
출처 : Matching Multiple Lines

Wednesday, March 16, 2016

perl 에서 텍스트파일 전체를 스트링으로 불러오는 법

다음과 같이 하면 됨.

use File::Slurp;
my $file_content = read_file('text_document.txt');

윈도우의 CRLF 개행문자를 처리해주려면 읽을때 다음과 같이 해줌

$text =~ s/\r\n/\n/g;

저장할때는 다음과 같이 변환해주면 됨

$text =~ s/\n/\r\n/g;

키워드 : text file, whole, load, windows, return characters
레퍼런스 : Read an entire file into a string

Sunday, March 13, 2016

perl의 regular expression에서 number of matches 얻는 법

다음과 같이 하면 됨
my $s = "Hi. This is me.";
my $n = scalar( @{[ $s=~/i/g ]} );

실행하면 $n 의 결과값은 3이 나옴

레퍼런스 : Is there a Perl shortcut to count the number of matches in a string?

Tuesday, June 16, 2015

현재 실행중인 perl 스크립트의 파일명 얻는 법

__FILE__ is the actual file that the Perl interpreter deals with during compilation, including its full path.
사용예:
use File::Basename;
my $dirname = dirname(__FILE__);
레퍼런스 : How do I get the full path to a Perl script that is executing?

Regex to match any character including new lines

/s modifier 를 사용하면 됨
$string =~ /(START)(.+?)(END)/s;
키워드 : 개행문자
검색어 : perl regular expression including newline
레퍼런스 : Regex to match any character including new lines

Saturday, February 21, 2015

TextMate 에서 코드 블럭 { } 로 감싸는 핫키

TextMate에서 코드 블럭 선택하고 { 누르면 {} 블럭이 만들어진다.
키워드 : shortcut, hotkey, 중괄호, code block, perl

Perl 에서 파일 패스 concatenate 하는 법

use File::Spec;
하고
print File::Spec->catdir(dirname, filename);
하면 됨


use File::Spec;
print File::Spec->catdir('dir1/dir2/dir3', '../filename'),"\n";
print File::Spec->catdir('dir1/dir2/dir3', '../../filename', ),"\n";

키워드 : file path, filepath, merge, append
출처 : How to concatenate pathname and relative pathname?

Monday, September 15, 2014

Perl 에서 array 에 insert 하기

splice 를 이용한다.
2번째 element 위치로 $s 를 insert 하려 한다면 다음과 같이 하면 된다.
 splice(@a, 2, 0, $s);  
여기서 세번째 argument인 0은 delete 할 element 의 수를 0으로 지정한 것이다.

splice 를 이용해서 n번째 라인에 스트링 추가하는 예제
 sub insertString_beforeLine
 {  
      my $s = shift;  
      my $n = shift;  
      my @a = split(/\n/, $source);  
      splice(@a, $n, 0, $s);  
      $source = join("\n", @a);  
 }  

Tuesday, September 2, 2014

perl 의 floor 함수

perl 에는 별도의 floor 나 ceil 함수가 없으므로 sprintf 를 써야 한다.
floor 와 같은 기능을 쓰려면 int 를 사용하면 된다. 예를 들어

$int_val = int( 6.23930 );

하면 결과는 6이 된다.

키워드 : ceiling, round function
출처 : http://www.tutorialspoint.com/perl/perl_int.htm

Sunday, August 31, 2014

perl 에서 double quote 와 single quote 의 차이

""는 regular expression 을 취급하지만 ''는 그렇지 않다.
즉 "\." 는 '.' 로 다시 쓸 수 있다.

Perl 의 loop statements

Perl 의 loop statements 예
     for (my $i = 10; $i >= 0; $i--) {  
       print "$i...\n";        # Countdown  
     }  
   
     foreach my $i (reverse 0..10) {  
       print "$i...\n";        # Same  
     }  
   
     %hash = (dog => "lazy", fox => "quick");  
     foreach my $key (keys %hash) {  
       print "The $key is $hash{$key}.\n"; # Print out hash pairs  
     }  

Thursday, August 15, 2013

Perl 에서 Array 에 element 를 add 하기

 sub addElmtToArray  
 {  
      my $pa = shift;  
      my $elmt = shift;  
      $pa->[scalar(@$pa)] = $elmt;  
 }  
키워드 : append

Perl 에서 element 를 remove 하기

 sub removeArrayElmt  
 {  
      my $array = shift;  
      my $index = shift;  
      splice(@$array, $index, 1);       
 }  
출처 : http://perlmaven.com/splice-to-slice-and-dice-arrays-in-perl

Wednesday, August 7, 2013

특정 개수 문자를 제외한 부분을 얻어내는 regular expression

뒷부분 6개의 문자를 제외한 것을 추출하는 regular expression
      $num =~ m/^(\d+)(\d{6})$/;  
      print $1; print "\n";  
      print $2; print "\n";  

Regular expressions in Perl


Regular expressions in Perl

This document presents a tabular summary of the regular expression (regexp) syntax in Perl, then illustrates it with a collection of annotated examples.

Metacharacters

charmeaning
^beginning of string
$end of string
.any character except newline
*match 0 or more times
+match 1 or more times
?match 0 or 1 times; or: shortest match
|alternative
( )grouping; “storing”
[ ]set of characters
{ }repetition modifier
\quote or special
To present a metacharacter as a data character standing for itself, precede it with \ (e.g. \.matches the full stop character . only).
In the table above, the characters themselves, in the first column, are links to descriptions of characters in my The ISO Latin 1 character repertoire - a description with usage notes. Note that the physical appearance (glyph) of a character may vary from one device or program or font to another.

Repetition

a*zero or more a’s
a+one or more a’s
a?zero or one a’s (i.e., optional a)
a{m}exactly m a’s
a{m,}at least m a’s
a{m,n}at least m but at most a’s
repetition?same as repetition but the shortestmatch is taken
Read the notation a’s as “occurrences of strings, each of which matches the pattern a”. Read repetition as any of the repetition expressions listed above it. Shortest match means that the shortest string matching the pattern is taken. The default is “greedy matching”, which finds the longest match. The repetition? construct was introduced in Perl version 5.

Special notations with \

Single characters
\ttab
\nnewline
\rreturn (CR)
\xhhcharacter with hex. code hh
“Zero-width assertions”
\b“word” boundary
\Bnot a “word” boundary
Matching
\wmatches any single character classified as a “word” character (alphanumeric or “_”)
\Wmatches any non-“word” character
\smatches any whitespace character (space, tab, newline)
\Smatches any non-whitespace character
\dmatches any digit character, equiv. to [0-9]
\Dmatches any non-digit character

Character sets: specialities inside [...]

Different meanings apply inside a character set (“character class”) denoted by [...] so that, instead of the normal rules given here, the following apply:
[characters]matches any of the characters in the sequence
[x-y]matches any of the characters from x to y (inclusively) in the ASCII code
[\-]matches the hyphen character “-
[\n]matches the newline; other single character denotations with \ apply normally, too
[^something]matches any character except those that [something] denotes; that is, immediately after the leading “[”, the circumflex “^” means “not” applied to all of the rest

Examples

expressionmatches...
abcabc (that exact character sequence, but anywhere in the string)
^abcabc at the beginning of the string
abc$abc at the end of the string
a|beither of a and b
^abc|abc$the string abc at the beginning or at the end of the string
ab{2,4}can a followed by two, three or four b’s followed by a c
ab{2,}can a followed by at least two b’s followed by a c
ab*can a followed by any number (zero or more) of b’s followed by a c
ab+can a followed by one or more b’s followed by a c
ab?can a followed by an optional b followed by a c; that is, either abc or ac
a.can a followed by any single character (not newline) followed by a c
a\.ca.c exactly
[abc]any one of ab and c
[Aa]bceither of Abc and abc
[abc]+any (nonempty) string of a’s, b’s and c’s (such as aabbaacbabcacaa)
[^abc]+any (nonempty) string which does not contain any of ab and c (such as defg)
\d\dany two decimal digits, such as 42; same as \d{2}
\w+a “word”: a nonempty sequence of alphanumeric characters and low lines (underscores), such as foo and 12bar8 and foo_1
100\s*mkthe strings 100 and mk optionally separated by any amount of white space (spaces, tabs, newlines)
abc\babc when followed by a word boundary (e.g. in abc! but not in abcd)
perl\Bperl when not followed by a word boundary (e.g. in perlert but not in perl stuff)

Examples of simple use in Perl statements

These examples use very simple regexps only. The intent is just to show contexts where regexps might be used, as well as the effect of some “flags” to matching and replacements. Note in particular that matching is by defaultcase-sensitive (Abc does not match abc unless specified otherwise).
s/foo/bar/;
replaces the first occurrence of the exact character sequence foo in the “current string” (in special variable $_) by the character sequence bar; for example, foolish bigfoot would become barlish bigfoot
s/foo/bar/g;
replaces any occurrence of the exact character sequence foo in the “current string” by the character sequence bar; for example, foolish bigfoot would become barlish bigbart
s/foo/bar/gi;
replaces any occurrence of foo case-insensitively in the “current string” by the character sequence bar(e.g. Foo and FOO get replaced by bar too)
if(m/foo/)...
tests whether the current string contains the string foo



출처 : http://www.cs.tut.fi/~jkorpela/perl/regexp.html

Perl 에서 maximum value of a scalar

maximum value of a scalar

For 32-bit version of Perl, the maximum integer (without using bigint or similar) that can be stored precisely is -253 on the negative side and 253 on the positive side.

    build settingsMax positive integerMax negative integer
    32-bit ints and double floats253 = 9,007,199,254,740,992-253 = -9,007,199,254,740,992
    64-bit ints and double floats264-1 = 18,446,744,073,709,551,615-263 = 9,223,372,036,854,775,808
    64-bit ints and quadruple floats2113 = 10,384,593,717,069,655,257,060,992,658,440,192-2113 = -10,384,593,717,069,655,257,060,992,658,440,192

Tuesday, May 21, 2013

Perl 에서 hash 의 element 수 구하기

 print scalar(keys %h);  
출처 : How can I find the number of elements in a hash?

Perl 에서 array 복사하기

다음과 같은 대입문은 어레이를 copy 즉 duplicate 함.
      my @a = (1, 2, 3, 4, 5);  
      my @b = @a;  
      for(my $i = 0; $i < scalar(@b); $i = $i + 1)  
      {  
           $b[$i] = $b[$i] + 100;  
      }  
      printArray(\@a);  
      printArray(\@b);  

Monday, May 20, 2013

Perl 에서 array 를 함수의 reference 로 pass 하는 법

 my @a = (10, 20, 30);  
 foo(\@a);  
 sub foo  
 {  
      my $pa = shift;  
      my @a = @$pa;  
      for(my $i = 0; $i < @a; $i = $i + 1)  
      {  
           print "$a[$i]\n";  
      }  
 }