顯示具有 perl 標籤的文章。 顯示所有文章
顯示具有 perl 標籤的文章。 顯示所有文章

2014年6月24日 星期二

perl 物件名稱和檔名

(備份自wordpress blog)


our @ISA = qw(Person2);    # inherits from Person 是package的名字

use Person;  //是package的檔名,在同一資料夾下。

===================================

# class Employee.pm
package Employee;
use Person;
use strict;
our @ISA = qw(Person2);    # inherits from Person

#constructor
sub new {
my ($class) = @_;

#call the constructor of the parent class, Person.
my $self = $class->SUPER::new();
$self->{_id}   = undef;
$self->{_title} = undef;
bless $self, $class;
print "Employee constructor\n";
return $self;
}

#accessor method for  id
sub id {
my ( $self, $id ) = @_;
$self->{_id} = $id if defined($id);
return ( $self->{_id} );
}

#accessor method for  title
sub title {
my ( $self, $title ) = @_;
$self->{_title} = $title if defined($title);
return ( $self->{_title} );
}

sub print {
my ($self) = @_;

# we will call the print method of the parent class
$self->SUPER::print;
$self->address->print;
}

1;
=========================================

#class Person.pm
package Person2;
use strict;
use Address;    #Person class will contain an Address

#constructor
sub new {
my ($class) = @_;
my $self = {
_firstName => undef,
_lastName  => undef,
_ssn       => undef,
_address   => undef
};
bless $self, $class;
print "Person2 constructor\n";
return $self;
}

#accessor method for Person first name
sub firstName {
my ( $self, $firstName ) = @_;
$self->{_firstName} = $firstName if defined($firstName);
return $self->{_firstName};
}

#accessor method for Person last name
sub lastName {
my ( $self, $lastName ) = @_;
$self->{_lastName} = $lastName if defined($lastName);
return $self->{_lastName};
}

#accessor method for Person address
sub address {
my ( $self, $address ) = @_;
$self->{_address} = $address if defined($address);
return $self->{_address};
}

#accessor method for Person social security number
sub ssn {
my ( $self, $ssn ) = @_;
$self->{_ssn} = $ssn if defined($ssn);
return $self->{_ssn};
}

sub print {
my ($self) = @_;

#print Person info
printf( "Name:%s %s\n\n", $self->firstName, $self->lastName );
}

1;
How do I use a Perl module from a relative location?
http://stackoverflow.com/questions/787899/how-do-i-use-a-perl-module-from-a-relative-location

use FindBin;
use lib "$FindBin::Bin/../lib"; // . /var/www/cgi-bin/project/guestbook/controller

print "\@INC is @INC\n";
// @INC is ../model /usr/local/lib/perl5 /usr/local/share/perl5 /usr/lib/perl5/vendor_perl /usr/share/perl5/vendor_perl /usr/lib/perl5 /usr/share/perl5

2013年9月15日 星期日

perl 開檔

http://tw.perlmaven.com/open-and-read-from-files
讀取檔案:

use strict;
use warnings;

my $filename = 'xxx.txt';
open(my $fh, '<:encoding(UTF-8)', $filename) || die "Could not open file '$filename' $!"; # $fh stand for filehandle

my $count = 0;

while (my $row = <$fh>) {
    chomp $row;
    print "$row\n";
    $count++;
}

close($fh);

( 上述編碼在blogspot用syntax highlight有bug,從HTML轉到撰寫時會變成亂碼 )

http://ind.ntou.edu.tw/~dada/cgi/Perlsynx.htm
$_ The default input and pattern-searching space.
$! Contains the current value of errno.

取代檔案:
http://stackoverflow.com/questions/4732937/how-do-i-read-a-file-line-by-line-while-modifying-lines-as-needed ( 使用Tie::File )
xxx.txt濾出來的內容存成ref ($v)後對bbb.txt一行一行去取代第二個match的城市

use Tie::File;
my @file_array;
tie @file_array, 'Tie::File', 'bbb.txt' || die "END! $!";

$country = '';
$count = 0;
my $city = '';
my $no_match_ref;
my $no_match_ref_count = 0;

$v = {
          'Bolivia' => {
                         'El Beni' => 'El Beni'
                       },          
          'Canada' => {
                        'Newfoundland' => 'Newfoundland',
                        'Yukon Territory' => 'Yukon Territory'
                      },
        };

for my $line (@file_array) {
#    s/測試/一二三/g;         # Replace PERL with Perl everywhere in the file
    
    # country line
    if( $line =~ /v ===/ ){
        my @country_arr= split(/"/, $line);
        $country =  $country_arr[1]; 
    }
    
     #city line
    if( $line =~ /ss\(f,\s\d/ ){
        my @city_arr = split(/"/, $line);
#        print $line,"\n";
        $city = $city_arr[1];
#        print "country:$country, city:$city, deftag:$v->{$country}{$city}\n"; # - #832
        
        if($v->{$country}{$city}){
            my $index = 2;
            $file_array[$count] =~ s/($city)/--$index == 0 ? $v->{$country}{$city}:$1/ge; 
        }
        
        if(!$v->{$country}{$city}){
            $no_match_ref->{$country}{$city} = $city;
            $no_match_ref_count++;
        }
        
        # &use_reg_exp_to_match(); # no use, because I will use SQL 
    }
    $count++;
    
}

print Dumper $no_match_ref;
print "\n no_match_ref counter:$no_match_ref_count"; # - #296


untie @file_array;

算ref 的key個數
$v = {
          'Bolivia' => {
                         'El Beni' => 'El Beni'
                       },          
          'Canada' => {
                        'Newfoundland' => 'Newfoundland',
                        'Yukon Territory' => 'Yukon Territory'
                      },
          ...
        };
$count = 0;
foreach my $val ( keys %{$v} ){ #方法一,用foreach跑
  $count++;
}
print "\n$count\n";
print scalar keys $v; #方法二

在sublime用正規式搜尋中文
http://stackoverflow.com/questions/1585914/matching-chinese-characters-with-regular-expressions-php
[\x{4e00}-\x{9fa5}] --> One char between 4E00 and 9FA5

http://www.regular-expressions.info/unicode.html
\p{Han} 是perl的用法 ( 未試驗 )

如何將有改過的檔案檔名做唯一輸出?
工具:cygwin, sublime, ( Komodo Edit 8, perl編輯器 )
1. 將資料夾拉到cygwin上,以直接cd 進入該目錄
2. $ ls -R work* > ls_files.txt
3. 開sublime,將ls_files.txt的檔名濾出來到 all_files.txt另存新檔
4. 寫 filter_template.pl 去開 all_files.txt檔案,讓修改過的樣板為唯一
use strict;
use warnings;

use Data::Dumper;

open(my $fh, "<:encoding data-blogger-escaped-all_files.txt="" data-blogger-escaped-count="" data-blogger-escaped-die="" data-blogger-escaped-exist="" data-blogger-escaped-file="" data-blogger-escaped-my="" data-blogger-escaped-my_array="" data-blogger-escaped-not="" data-blogger-escaped-or="" data-blogger-escaped-row="<$fh" data-blogger-escaped-while="">) {
    chomp $row;
    push @my_array, $row;
    $count++;
}
close($fh);

sub uniq {
    return keys %{{ map { $_ => 1 } @_ }};
}

print join(" ", uniq(@my_array)), "\n";


5. $ perl filter_template.pl > result.txt
result.txt即為結果。讀檔進來的$row尾端會換行(未解決)
參考:
push 值到陣列
http://perl.hcchien.org/ch03.html
push @my_array, $row;
How do I remove duplicate items from an array in Perl?
http://stackoverflow.com/questions/7651/how-do-i-remove-duplicate-items-from-an-array-in-perl
sub uniq {
    return keys %{{ map { $_ => 1 } @_ }};
}

@my_array = ("one","two","three","two","three");
print join(" ", @my_array), "\n";
print join(" ", uniq(@my_array)), "\n";




2013年9月14日 星期六

URL decode

例如一個網址字串為
https://www.google.com.tw/?gws_rd=cr&ei=Mkk0UuLLForgkAWZi4D4DQ#q=test+url+decode

要將他解成一般字串
1. 使用線上URL decode工具:
http://meyerweb.com/eric/tools/dencoder/
2. 使用perl URL::Encode 模組
安裝
$ cpan
cpan> install URL::Encode

use URL::Encode qw/url_decode/; #如果只有寫 use URL::Encode ,則需使用URL::Encode::url_decode()去叫函數

$url = "URL字串";

print url_decode($url);
print "\n";

cpan安裝的模組會裝在哪?
http://blog.longwin.com.tw/2008/03/debian_linux_perl_cpan_newbie_2008/
site (於 local 直接 "# cpan> install Package 安裝" 或 "sudo perl -MCPAN -e 'CPAN::Shell->install("Text::Wrap")' 安裝", 會往下述路徑裝)

1. Modules installed by the local administrator for the current version of Perl
2. /usr/local/lib/perl/version
3. /usr/local/share/perl/version
4. Where version indicates the current Perl version ($Config{version}).

2013年9月2日 星期一

perl 使用指令和Storable模組儲存perl格式資料到檔案

因為mysql撈出來中文資料有亂碼
所以想將他存到檔案中,再試看哪個模組( Text::Iconv(有些字會失敗)或 Unicode::MapUTF8 )可以正常轉換成utf-8

perl -MStorable -e '$text = "BEAR!!";  $target = "/home/your_name/git/data.txt"; Storable::nstore({text=>$text}, $target);'
nstore第一個參數必須使用hash,不然會出錯(error log裡面沒報錯,但沒執行nstore,似乎要用eval())

perl -MStorable -e '$target = "/home/your_name/git/data.txt"; $info = &Storable::retrieve($target); print $info->{text}'

使用terminal在mysql上下SQL出現亂碼:
Rellik: 因為terminal預設是utf8,但資料庫存big5進去,所以會亂碼
方法1. 使用Rellik的.screenrc 在那個分頁按 alt+a b =>轉成big5 ,然後ctrl+l 清畫面,再下一次SQL,就正常了
方法2. 在putty上字形要設定細明體(非新細明體),然後windows -- Translation 的地方選use font encoding(最下面那個),缺點是出來的字正常但複製到記事本上是亂碼。(但Ike的不會)
細明體才會是big5,選Courier則否

更多:
http://help.cs.nctu.edu.tw/help/index.php/Setting_-_%E5%B7%A5%E4%BD%9C%E7%AB%99%E7%B7%A8%E7%A2%BC%E8%A8%AD%E5%AE%9A(UTF-8)
工作站編碼設定(UTF-8)

http://help.cs.nctu.edu.tw/help/index.php/Setting_-_%E5%9C%A8%E5%B7%A5%E4%BD%9C%E7%AB%99_UTF-8_%E7%92%B0%E5%A2%83%E8%A8%AD%E5%AE%9A%E4%B8%8B%E4%BD%BF%E7%94%A8_Big5
在工作站 UTF-8 環境設定下使用 Big5 - 用法與Rellike的.screenrc檔案相同

http://www.bootf.com/67.html
Putty在默认情况下没有使用UTF-8编码,因此在显示中文的时候会出现乱码。 ( 與Rellik說法有出入 )

如何印出$ENV變數 ( 部份變數參照export內的設定 )
老天尊: Do you know how to dump $ENV in perl?
Chase: print DUMPER(\%ENV)
老天尊: ok, thanks.
老天尊: I have a question.. why we can't dumper $ENV directly?
Chase: you can
Chase: $ENV is a hash though
Chase: now a scalar var
老天尊: print STDERR Dumper $ENV
echo nothing.
Chase: because it is %ENV
老天尊: ohoh
Chase: it's a hash and NOT a hashref
解法:
$ perl -MData::Dumper -e 'print Dumper \%ENV'