레이블이 PERL인 게시물을 표시합니다. 모든 게시물 표시
레이블이 PERL인 게시물을 표시합니다. 모든 게시물 표시

2009년 8월 5일 수요일

html strip

  1. use HTML::Strip;

    $raw_html = "<tr style='xx' size='xx'>aa</tr>";
    my $hs = HTML::Strip->new();
    my $clean_text = $hs->parse( $raw_html );
    # $hs->eof;

    print $clean_text;

 

평소 패턴매칭으로 사용했으나 lib가 있었다.

패턴 매칭이 더 나은가?

  1. $value =~ s/\<[^\<]+\>//g;

이 글은 스프링노트에서 작성되었습니다.

2009년 7월 15일 수요일

Excel을 xml로 저장하기.

php의 엑셀 파서는 너무 후지다. 무슨 이유에선지 원본 파일의 내용과 파싱한 내용이 다르다.
다른 이름으로 저장을 해봤더니 정상적으로 읽어진다. 하지만 고객들에게 매번 저장을 새로 하라고 할 수는 없는 노릇이다.

perl로 테스트를 해 봤더니 원본도 이상없이 파싱이 된다. 흠 php엑셀 파서를 perl로 변경해야 할까?

#!/usr/bin/perl -w

    use strict;
    use Spreadsheet::ParseExcel;
    use Spreadsheet::ParseExcel::FmtUnicode;
    my $oExcel = new Spreadsheet::ParseExcel;
    my $oFmt = Spreadsheet::ParseExcel::FmtUnicode->new(Unicode_Map => "euc-kr");
    use XML::Excel;
    my $parser   = Spreadsheet::ParseExcel->new();
    my $excel_obj = XML::Excel->new({ParseExcel => $parser});

    my @arr_data;
    my $workbook = $parser->Parse('20090713101853_10002.XLS',$oFmt);

    for my $worksheet ( $workbook->worksheets() ) {

        my ( $row_min, $row_max ) = $worksheet->row_range();
        my ( $col_min, $col_max ) = $worksheet->col_range();

        for my $row ( $row_min .. $row_max ) {
            my @_row;
            for my $col ( $col_min .. $col_max ) {
                my $cell = $worksheet->get_cell( $row, $col );
                next unless $cell;
                push(@_row, $cell->value());

                #print "Row, Col    = ($row, $col)\n";
                #print "Value       = ", $cell->value(),       "\n";
                #print "Unformatted = ", $cell->unformatted(), "\n";
                print "#";
            }

            $arr_data[$row] = \@_row;
        }
    }
    $excel_obj->{column_data} = \@arr_data;
    $excel_obj->print_xml('aa.xml');

2009년 6월 17일 수요일

Spreadsheet::WriteExcel 사용시 한글 sheet명

my $map   = Unicode::Map->new("EUC-KR");
 $sheet_name = $map->to_unicode("한글sheet명");
 $worksheet = $workbook->add_worksheet( $sheet_name, 1 );   

crontab에 작업 watchdog 설정.

perl로 watchdog 프로그램을 하나 만든 후 crontab에 작업을 등록함
[root@pimz13 ~]# crontab -e
00,5,10,15,19,20,25,30,35,38,40,45,50,55 * * * * /usr/bin/perl /root/watchdog.sh
5분에 한 번씩 watchdog을 실행 함

crontab은 환경을 전혀 load하지 않는다. 그러므로 shell 프로그램에서 사용자 환경을 load 한 후
perl로 만든 프로세스 관리 프로그램을 실행해야 함.

#!/bin/sh
. ~root/.bash_profile
perl /root/watchdog.pl

등록되지 않은 프로세스들을 검사해서 자동으로 실행한다.


2009년 5월 22일 금요일

perl에서 utf-8 을 cp949 로 변경하기 Text::Iconv사용

use Text::Iconv;
$c = Text::Iconv->new("utf8","cp949");
$_datas = $c->convert( $str_utf8);

Encode 모듈에서 오류 나던것들이 해결 됨.

2009년 5월 20일 수요일

perl 날짜 계산하기..

#!/usr/bin/perl -w

use strict ;
use Date::Calc qw(Add_Delta_Days) ;

my ( $todayd, $todaym, $todayy ) = (localtime)[3..5] ;
$todaym += 1 ;
$todayy  += 1900 ;

my ($yesty,$yestm,$yestd) = Add_Delta_Days($todayy,$todaym,$todayd, -1) ;



어제 구하기..

2009년 5월 12일 화요일

ActivePerl사용시 DBD::mysql 설치

DBD::mysql - A Perl5 Database Interface to the MySQL database
=============================================================

The driver installation is described in

  INSTALL.html

In short: If you are using

  Windows/ActivePerl

    1.) If you need to use an HTTP Proxy, set the environment
        variable http_proxy, for example like this:

          set http_proxy=http://myproxy.com:8080/

    2.) The actual installation is as simple as

   ppm install DBI
          ppm install DBD::mysql

        As of this writing, the above procedure won't work with
        ActivePerl 5.8.0, because so far a PPM for DBD::mysql is
        not available from the ActiveState server. I don't know
        why. However, Randy Kobes has kindly donated a PPM package
        to his own repository. You can use this as follows:

          ppm install http://theoryx5.uwinnipeg.ca/ppms/DBD-mysql.ppd

2009년 4월 22일 수요일

정규식 샘플

$input = "<option value='3/0/1/씨제이택배(CJ-GLS)' selected>씨제이택배(CJ-GLS)</option>
$input =~ /([\d]{1}\/[\d]+\/[\d]{1}\/[\W\w]+)selected/;

2009년 2월 17일 화요일

post with json

요즘엔 json방식으로 request들을 많이 하는군요
xe에서도 최근 기능 추가를 했죠 :)

$json_req = "{}"; // json string
$ie->request (
               POST
               '[url]',
               Content_Type => 'application/json; charset=utf-8',              
               Content          => $json_req,
        );

2008년 12월 5일 금요일

[패턴] euc-kr의 패턴 매칭 예제 2

use Encode qw/encode decode/;

my $utf8   = decode("euc-kr", $content);
my $cnt = 0;

# utf-8 로 format이 변경되면 [\w]에서 인식 가능한 상태가 됨
while ($utf8 =~ /_OBJ_GRID.setTextOnly\(\"([\w]+)\", ([\w]+), \"([\w\(\)\-]+)\"\);/g) {
    # 한글을 화면으로 보려면 다시 euc-kr로 변경해야 한다
    my $val = encode("euc-kr", $3);
    print $val . "\n";
    $cnt++;
}


2008년 12월 4일 목요일

[패턴] 한글이 포함된 string의 패턴 매칭

이게 아닌데 이게 아닌데 아무리 해봐도 의도한 대로 결과가 나와 주지 않는다.
한글을 사용하기 위해선 encoding 모듈을 사용해야 하는 것을..쯧쯔..하루 종일 뭔 삽질인지
날도 추운데..

use encoding 'euc-kr'; # 이 놈이 모든것을 해결해 줌
$content = "_OBJ_GRID.setTextOnly('ordNm', maxRow, '장은정(cchang700)');_OBJ_GRID.setTextOnly('ordNm', maxRow, '장은정(cchang700)');_OBJ_GRID.setTextOnly('ordNm', maxRow, '장은정(cchang700)');";


while ($content =~ /_OBJ_GRID.setTextOnly\('([\w]+)', ([\w]+), '([\w\(\)\-]+)'\);/g) {
    print "Word is $1, $2 , $3 ends at position ", pos $content, "\n";
}



결과

================
 _OBJ_GRID.setTextOnly('ordNm', maxRow, '장은정(cchang700)');_OBJ_GRID.setTextOnly('ordNm', maxRow, '장은정(cchang700)')
;_OBJ_GRID.setTextOnly('ordNm', maxRow, '장은정(cchang700)');
===================
Word is ordNm, maxRow , 장은정(cchang700) ends at position 57
Word is ordNm, maxRow , 장은정(cchang700) ends at position 114
Word is ordNm, maxRow , 장은정(cchang700) ends at position 171

알고나면 뭐든 쉬운 것을 쯧쯔....

2008년 11월 21일 금요일

s와 tr 의 차이

이런것도 큰 차이를 모르고 쓰고 있었다니..흠흠..
왜 난 근본적인 질문이 없었을까..
일단 s나 tr 모두 스트링에서 패턴 매치를 통해 뭔가를 바꾸는 건데..
둘이 모두 가능한 일이 있고 안되는 일이 있고..흠흠..

사실 replace는 둘을 적절히 조합해서 사용하면 될듯.

$string =~ s/a/b/g;
$string =~ tr/a/b/;

tr은 g키워드(모두 변경)을 사용하지 않아도 되는구만...s가 더 상위의 기능일까?

a로 시작하고 z로 끝나는 워드 찾아서 z로 변경
$string =~ s/a(..c)/z$1/g;
$string =~ tr/
a(..c)/z$1/;

사용자 삽입 이미지
소스 ...







사용자 삽입 이미지
결과


a를 그냥 z로 다 바꿔버리네...바보 됨..

s키워드의 케이스..
사용자 삽입 이미지
소스





사용자 삽입 이미지
잘 되는 구만....


결론 tr은 뇌가 없다

2008년 11월 14일 금요일

perl] pack과 unpack을 왜 사용하는가?

사용법도 어렵지만 무엇보다 왜 쓰는지를 알아야 알아야 할지 말아야 할지를 선택할 것 아냐!!!! 헌데 정말이이 언제 어디서 무엇을 위해 사용하는것인지..생각해 봐야겠다.

참조: http://www.perlmonks.org/?node_id=224666


Pack/Unpack Tutorial

A recent conversation in the chatterbox gave me the idea to write this. A beginning programmer was trying to encode some information with pack and unpack but was having trouble coming to grips with exactly how they work. I have never had trouble with them but I came to programming from a hardware background and I'm very familiar with assembly and C programming. People who have come to programming recently have probably never dealt with things at such a low level and may not understand how a computer stores data. A little understanding at this level might make pack and unpack a little easier to figure out.

Why we need pack and unpack

Perl can handle strings, integers and floating point values. Occassionally a perl programmer will need to exchange data with programs written in other languages. These other languages have a much larger set of datatypes. They have integer values of different sizes. They may only be capable of dealing with fixed length strings (dare I say COBOL?). Sometimes, there may be a need to exchange binary data over a network with other machines. These machines may have different word sizes or even store values differently. Somehow, we need to get our data into a format that these other programs and machines can understand. We also need to be able to interpret the responses we get back.

Perl's pack and unpack functions allow us to read and write buffers of data according to a template string. The template string allows us to indicate specific byte orderings and word sizes or use the local system's default sizes and ordering. This gives us a great deal of flexibility when dealing with external programs.

In order to understand how all of this works, it helps to understand how computers store different types of information.

2008년 11월 11일 화요일

[perl] trim function 구현...

의외로 내장 함수가 없구만..
장난해? ㅋㅋㅋ

# Perl trim function to remove whitespace from the start and end of the string
sub trim($)
{
my $string = shift;
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return $string;
}
# Left trim function to remove leading whitespace
sub ltrim($)
{
my $string = shift;
$string =~ s/^\s+//;
return $string;
}
# Right trim function to remove trailing whitespace
sub rtrim($)
{
my $string = shift;
$string =~ s/\s+$//;
return $string;
}

2008년 11월 4일 화요일

[soap] asmx 와 soap::lite 사용

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

use SOAP::Lite 'trace', 'debug';

my $server = SOAP::Lite
    ->uri('http://ws.robstones-services.co.uk/External')    
    ->proxy('http://ws.robstones-services.co.uk/external.asmx');

my $returned = $server ->getCallList({ 'Username' => 'RobsUser', 'Password' => 'RobsPassword' });

foreach my $type ($returned->valueof('//getCallListResult/string'))
{
    next unless ($type); ## ignore any undefs
    print "$type\n";
 }

2008년 6월 17일 화요일

perl JSON module 사용 from_json으로 파싱된 데이터 사용

# $str_json에는 json형식의 string 데이터가 들어간다.
# orderingConfirmList의 key에 array의 형식으로 데이터가 들어있음[{"ORDER_NO":"11"},{"ORDER_NO":"2"}] 모 이쯤 되겠지.
# 그라지~~~

my $_scalar = from_json( $_str_json );
my @values = @{$_scalar->{'orderingConfirmList'}};

foreach my $_v ( @values )
{
        # print Dumper ( $_v );
        print $_v->{ORD_NO}. "\n";
}

2008년 6월 9일 월요일

앞으로 DBI대신에 DBix::class를 사용하기로 함.

DBIx::Class - Extensible and flexible object <-> relational mapper.
확장이 가능하다라, 어떻게 확장을 하겠다는 이야기인지?

샘플:
step 1. 먼저 사용자 객체를 생성한다.
1. Create a schema class called DB/Main.pm:

package DB::Main;
  use base qw/DBIx::Class::Schema/;

  __PACKAGE__->load_classes();

  1;

2. Create a table class to represent artists, who have many CDs, in DB/Main/Artist.pm:

package DB::Main::Artist;
  use base qw/DBIx::Class/;

  __PACKAGE__->load_components(qw/PK::Auto Core/);
  __PACKAGE__->table('artist');
  __PACKAGE__->add_columns(qw/ artistid name /);
  __PACKAGE__->set_primary_key('artistid');
  __PACKAGE__->has_many(cds => 'DB::Main::CD');

  1;

3. DB/Main/CD.pm 에 CD class 생성

package DB::Main::CD;
  use base qw/DBIx::Class/;

  __PACKAGE__->load_components(qw/PK::Auto Core/);
  __PACKAGE__->table('cd');
  __PACKAGE__->add_columns(qw/ cdid artist title year /);
  __PACKAGE__->set_primary_key('cdid');
  __PACKAGE__->belongs_to(artist => 'DB::Main::Artist');

  1;



step 2. 프로그램 내부에서 사용
###################################################
# Connect to your database.
  use DB::Main;
  my $schema = DB::Main->connect($dbi_dsn, $user, $pass, \%dbi_params);
# dbi_params는 어떤것이지?

# Query for all artists and put them in an array,
  # or retrieve them as a result set object.
  my @all_artists = $schema->resultset('Artist')->all;
  my $all_artists_rs = $schema->resultset('Artist');

# where 조건을 만들어 넣는군..흠흠..
# Create a result set to search for artists.
  # This does not query the DB.
  my $johns_rs = $schema->resultset('Artist')->search(
    # Build your WHERE using an SQL::Abstract structure:
    { name => { like => 'John%' } }
  );

# Fetch only the next row.
  my $first_john = $johns_rs->next;

등등..흠 초기에 설정만 잘 해 놓으면 쉽게 사용이 가능하겠군.
굳이 좋은 점이라면 여러군데 산재되어 있는 query의 컨트롤 가능?




2008년 4월 18일 금요일

WWW::Mechanize 를 사용한 input 처리

실제 html 폼
<html>
<head><title>test</title>
<body>
<form>
   <input type=hidden name="hidden1" value="v_h1">
   <input type=text name="txt1" value="v_txt1">
   <input type=text name="txt2" value="v_txt2">
   <input type=hidden name="hidden2" value="v_txt2">
   <input type=checkbox name="chk1" value="v_chk1" >
   <input type=checkbox name="chk1" value="v_chk2" checked>
   <input type=radio name="rdo1" value="v_rdo1" >
   <input type=radio name="rdo1" value="v_rdo2" checked>
   <textarea name='txt_desc'>haha</textarea>
</form>
</body>
</html>
스크리핑 실행하는 perl 모듈
use WWW::Mechanize;
use Data::Dumper;

#############################
# begin of test part
# form 값을 parsing
my $agent = WWW::Mechanize->new( ); 
$agent->get( "http://scm.ezadmin.co.kr/test_form.html" );

my @forms = $agent->forms();
my $form = $forms[0];

print Dumper $form;

print "\n ============================ \n";

# Check all the boxes
foreach my $input ( @{$form->{inputs}} ) {
    print $input->{name} , "/" ;

    # hidden, text 처리
    if ( $input->{type} eq "text" or $input->{type} eq "hidden" or $input->{type} eq "textarea" )
    {
        print $input->{value}, "\n";
    }
    elsif ( $input->{type} eq "checkbox" or $input->{type} eq "radio" )
    {
        my $current = $input->{current};
        print $input->{menu}[$current]->{value} . "\n";
    }
}




2008년 4월 8일 화요일

Linux에서 한글 excel 읽어 들이기

Linux에서 한글 excel을 읽으면 한글이 전부 깨진다...흠흠..

아래와 같은 방법으로 엑셀을 읽어 들이면 된다. 테스트 해보니 original과 변경된 값을 모두 볼 수 있음

훌륭함~~~

use Spreadsheet::ParseExcel;
use Spreadsheet::ParseExcel::FmtUnicode;               
my $oExcel = new Spreadsheet::ParseExcel;

my $oFmt = Spreadsheet::ParseExcel::FmtUnicode->new(Unicode_Map => "euc-kr");
my $oBook = $oExcel->Parse("kshsame.xls", $oFmt);

    my($iR, $iC, $oWkS, $oWkC);
    print "FILE  :", $oBook->{File} , "\n";
    print "COUNT :", $oBook->{SheetCount} , "\n";
    print "AUTHOR:", $oBook->{Author} , "\n";
    for(my $iSheet=0; $iSheet < $oBook->{SheetCount} ; $iSheet++) {
        $oWkS = $oBook->{Worksheet}[$iSheet];
        print "--------- SHEET:", $oWkS->{Name}, "\n";
        for(my $iR = $oWkS->{MinRow} ;
                defined $oWkS->{MaxRow} && $iR <= $oWkS->{MaxRow} ; $iR++) {
            for(my $iC = $oWkS->{MinCol} ;
                            defined $oWkS->{MaxCol} && $iC <= $oWkS->{MaxCol} ; $iC++) {
                $oWkC = $oWkS->{Cells}[$iR][$iC];
                print "( $iR , $iC ) =>", $oWkC->Value, "\n" if($oWkC);  # Formatted Value
                print "( $iR , $iC ) =>", $oWkC->{Val}, "\n" if($oWkC);  # Original Value
            }
        }
    }


2008년 4월 1일 화요일

날짜 계산

# Date::Simple 을 사용하면 쉽게 계산 할 수 있다.
use Date::Simple ('date', 'today');

my $today = today();
my $yesterday = $today - 1;
my $start_date = $today - 15;