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

2022年4月27日 星期三

Perl to EXE

Reference:
 
本來裝 ActivePerl 5.34,但是它不給裝 PAR::Packer (perl to exe),只好改用 Strawberry Perl
  • download Strawberry Perl and install
  • 開啟 CPAN client,執行 install PAR::Packer 安裝

2019年6月27日 星期四

Perl send mail via gmail (use Net::SMTPS)

狀況:
更新 perl module 後無法用 Net::SMTP::TLS 透過 gmail 寄信。

錯誤訊息:
invalid SSL_version specified at C:/Perl/site/lib/IO/Socket/SSL.pm line 575

原因:
Net::SMTP::TLS 有 bug,和新的 IO::Socket::SSL 不合。

解法:
改用 use Net::SMTPS。使用方法和 Net::SMTP::TLS 幾乎一樣
只需修改紅色的那三行。


use Net::SMTPS;

$gmail_from = 'myaccount@gmail.com';
$mail_subject = "Subject Here";

$smtp = new Net::SMTPS (
'smtp.gmail.com',
Port    => 465,
doSSL => 'ssl',
Timeout => 10
);

$smtp->auth ( 'myaccount@gmail.com', 'mypassword' );
#  -- Enter email FROM below.   --
$smtp->mail('chdu.tw@gmail.com');

$smtp->to('email1', 'email2');

$smtp->data();

#This part creates the SMTP headers you see
$smtp->datasend("From: $gmail_from \n");
$smtp->datasend("Content-Type: text/html \n");
$smtp->datasend("Subject: $mail_subject");
# line break to separate headers from message body
$smtp->datasend("\n");
$smtp->datasend("Test");

$smtp->datasend("\n");
$smtp->dataend();

$smtp->quit;


2019年6月19日 星期三

Perl MIME:LITE 中文標題 亂碼

Reference:
使用 perl 发送中文邮件标题乱码
Email主旨亂碼 =?Big5?(Q|B)?xxxxxxxxxx ?=

狀況:
用 MIME:LITE 發信,中文標題變成亂碼

解法:
use MIME::Lite;
use MIME::Base64;

$mail_host = "My_SMTP_server";
$mail_from = 'from_address';
$mail_to = 'to_address';
$mail_subject = '=?big5?B?'. encode_base64("繁體中文標題") .'?=';
$mail_body = "Test";

mail_notify();

sub mail_notify {
MIME::Lite->send('smtp', $mail_host, Debug=>0, Timeout=>60);
$msg = MIME::Lite->new(
From     => $mail_from,
To       => $mail_to,
Subject  => $mail_subject,
Type     =>'multipart/mixed',
);
$msg->attach (
Type => 'TEXT',
Data => $mail_body,
) or die "Error adding the text message part: $!\n";
$msg->send();
}

2017年3月25日 星期六

Perl Net::SMTP::TLS attach file

Reference;
http://www.perlmonks.org/?node_id=784574

用 $smtp->datasend 傳附檔內容時,因為 gmail 接收資料有長度限制,如果一次傳送大量資料會出錯。變通辦法是用 split 將資料分段送出。


use Net::SMTP::TLS;
use MIME::Lite;

$gmail_from = 'account@gmail.com';
@gmail_bcc_png = ('bcc@gmail.com');
$mail_subject = "<mail_subjuct>";

$msg = MIME::Lite->new(
From       => $gmail_from,
    To         => $gmail_from,
    Subject    => $mail_subject,
Type     =>'multipart/mixed',
);
$msg->attach(
Type => 'image/png',
Path => '<file full path>',
Filename => 'report1.png',
Disposition => 'attachment'
);

$smtp = new Net::SMTP::TLS(
'smtp.gmail.com',
Port    => 587,
User    => '<account@gmail.com>',
Password=> '<password>',
Timeout => 30
);

$smtp->mail($gmail_from);

$smtp->bcc(@gmail_bcc_png);

$smtp->data();
  @tmp = split(/\n/, $msg->as_string);
foreach $line (@tmp) {
$line = $line . "\n";
$smtp->datasend( $line );
}
$smtp->dataend();

$smtp->quit;

2016年2月24日 星期三

Perl 取出 HTML 檔案的 table 內容

Reference:
HTML::TableExtract is beautiful

HTML::TableExtract 可以把 HTML 檔案理的 table 內容取出,非常方便。

Example:
#!/usr/bin/env perl

use strict; use warnings;
use HTML::TableExtract;

my $te = HTML::TableExtract->new(
    attribs => { id => 'tbl' },
);

# local copy of
# http://bea.gov/iTable/iTableHtml.cfm?reqid=9&step=3&isuri=1&903=58

$te->parse_file('personal-income.html');

my ($table) = $te->tables;

for my $row ($table->rows) {
    my ($undef, $label, @row) = @$row;
    next unless defined $label;
    if ($label eq 'Unemployment insurance') {
        print "$label\t@row\n";
    }
}

2016年1月27日 星期三

Perl scheduler task problem under Windows 2012

有一支 perl script 從 Windows 2003 搬到 Windows 2012 執行有錯誤。
手動執行是正常的,但是從 scheduler task 執行卻發生錯誤。

檢查發現從 scheduler task 執行 perl script,會在檢查目錄是否存在時發生錯誤。
測試發現 scheduler task 沒有網路磁碟機的連線,因為這個目錄在網路磁碟機上,
所以會找不到目錄。

解法:
用 batch file 把 perl script 包起來,scheduler task 改為執行 batch file。
batch file 內容:
net use N: \\server\share_dir
perl C:\tmp\my_script.pl

2015年1月19日 星期一

Send HTML POST data by Perl LWP

Reference:
How do I send POST data with LWP?

use LWP::UserAgent;
$ua = LWP::UserAgent->new();
$url = "http://www.twse.com.tw/ch/trading/exchange/MI_INDEX/MI_INDEX.php";

$today7 = "1040115";
$response = $ua->post( $url, { 'download' => 'csv',  'qdate' => $today7, 'selectType' => 'ALLBUT0999'} );
$content  = $response->decoded_content();
my $file = 'stocks_twse.csv';
open $FH_o, ">", $file;
print $FH_o $content;
close $FH_o;

2014年12月17日 星期三

Perl/TK的Entry無法輸入問題

Reference:
Perl/TK的Entry無法輸入問題

在Perl程式中加入以下設定,Entry就能輸入了

$ENV{"XMODIFIERS"}='@im=none';

原因:
之前裝 Acrobat reader 時加上中文支援 yum install "@Chinese Support" 造成的。

2014年10月24日 星期五

Perl directory list - List all files that match a filename pattern

Reference:
http://alvinalexander.com/blog/post/perl/generate-all-html-files-in-directory

#!/usr/bin/perl -w

opendir(DIR, ".");
@files = grep(/\.html$/,readdir(DIR));
closedir(DIR);

foreach $file (@files) {
   print "$file\n";
}

2014年7月7日 星期一

Perl XML parse

Reference:
http://stackoverflow.com/questions/487213/whats-the-best-xml-parser-for-perl
http://stackoverflow.com/questions/10404152/perl-script-to-parse-xml-using-xmllibxml

use XML::LibXML;

$xmlfilename = "2639.XML";

$parser = XML::LibXML->new();
$doc = $parser->parse_file($xmlfilename);

@nodes = $doc->findnodes("/Statistics/Stats/Sample");

print $nodes[0]->nodeName(), ": ", $nodes[0]->textContent(), "\n";

2014年6月6日 星期五

perl csv to excel saveas overwrite

Reference:
http://www.perlmonks.org/bare/?node_id=823261

use Win32::OLE qw(in with);
use Win32::OLE::Const 'Microsoft Excel';

# global setting
$Win32::OLE::Warn = 3; # die on errors...
# get already active Excel application or open new
my $Excel_to_write = Win32::OLE->GetActiveObject('Excel.Application') || Win32::OLE->new('Excel.Application', 'Quit');
$Excel_to_write->{SheetsInNewWorkBook} = 1;
$Excel_to_write->{Visible} = 1;
$Excel_to_write->{DisplayAlerts} = 0;

my $Book_to_write = $Excel_to_write->Workbooks->Add;
my $Sheet_to_write = $Book_to_write->Worksheets(1);
open (CSV, "C:/tmp/ASSY.CSV");
$col = $row = 1;
while (<CSV>) {
chomp;
my @line = split(",",$_);
for $cell (@line){
$Sheet_to_write->Cells($row,$col)->{'Value'} = $cell;
$col++;
}
$row++; $col = 1;
}
close(CSV);
$Book_to_write->SaveAs( {
Filename => "C:\\tmp\\Assy.xls",
FileFormat => xlWorkbookNormal}
);
$Book_to_write->Close;

2014年3月26日 星期三

perl hash print all values

Reference:
http://alvinalexander.com/blog/post/perl/how-print-values-items-elements-perl-hash

#!/usr/bin/perl

# create our perl hash

$prices{"pizza"} = 12.00;
$prices{"coke"} = 1.25;
$prices{"sandwich"} = 3.00;

while (($key, $value) = each (%prices))
{
  print "$key costs $prices{$key}\n";
}

2014年3月13日 星期四

perl pos function to parse directory path

目地:從 file full path 取出 directory

$backup_file = "D:/Auto/aaa/bbbb/20121121.xls";
while ($backup_file =~ /\//g) {
$dir_end = pos($backup_file);
}

$bakdir = substr($backup_file, 0, $dir_end);
print $bakdir;

Reference:
http://blog.xuite.net/abliou/perl/23232393

2013年11月21日 星期四

Perl Arrays of Hashes & array sort

Reference:
http://docstore.mik.ua/orelly/perl/prog3/ch09_03.htm

@AoH = ();
push @AoH, { ID => "1201", range => 7, price => 50 };
push @AoH, { ID => "1202", range => 5, price => 20 };
push @AoH, { ID => "1203", range => 6, price => 30 };
print $AoH[1]{price};

# hash %row
$row{ID} = "1204";
$row{range} = 4.3;
$row{price} = 70;
push @AoH, \%row;    # add %row to array by address
print $AoH[4]{range};
print $#AoH;   # array items number

# sort array by range
@AoH = sort {$b->{range} <=> $a->{range}} @AoH;
print $AoH[0]{ID};
print $AoH[1]{ID};
print $AoH[2]{ID};

2013年11月12日 星期二

Perl fails to open excel file when executing from Windows Task Scheduler

Reference:
Link1 Link2 Link3 Link4

狀況:
Perl 用 Win32::OLE 讀取 Excel 檔案,測試過可以正常執行,但是放到 排程工作 卻不執行。

解法:
1. Create directory "C:\Windows\SysWOW64\config\systemprofile\Desktop " (for 64 bit Windows) or "C:\Windows\System32\config\systemprofile\Desktop " (for 32 bit Windows)
2. Set Full control permissions on directory Desktop for the account running perl in background (for example in Win7 & IIS 7 & DefaultAppPool set permissions for user "IIS AppPool\DefaultAppPool")

2013年11月11日 星期一

Perl read / write Excel file

Reference:
http://blog.dwightmann.com/entry.asp?id=60
http://stackoverflow.com/questions/9761443/issues-reading-time-value-in-perl-using-win32ole

use Win32::OLE qw(in with);
use Win32::OLE::Const 'Microsoft Excel';

$Win32::OLE::Warn = 3; # die on errors...

$excel_file = "c:/tmp/myexcel.xls";

my $Excel_to_read = Win32::OLE->GetActiveObject('Excel.Application') || Win32::OLE->new('Excel.Application', 'Quit');
my $Book_to_read = $Excel_to_read->Workbooks->Open($excel_file);
my $Sheet_to_read = $Book_to_read->Worksheets(1);

print $Sheet_to_read->Cells(5,3)->{'Value'};

註:針對欄位格式為自訂,必須用$Sheet_to_read->Cells(5,3)->{'Text'}

2013年11月4日 星期一

Perl CPAN urllist reconfig

Reference:
http://major.io/2008/06/16/adjusting-cpan-mirror-list/

執行 cpan
Display your current mirrors:
cpan> o conf urllist

Delete the first mirror in your list:
cpan> o conf urllist shift

Delete the last mirror in your list:
cpan>  o conf urllist pop

Reconfig:
cpan> o conf init

2013年11月1日 星期五

Perl send mail via gmail

Reference:
http://dipinkrishna.com/blog/2010/12/sending-emails-gmail-smtp-perl/

use Net::SMTP::TLS;   # ActivePerl 5.14 才有

my $smtp = new Net::SMTP::TLS(
'smtp.gmail.com',
Port    => 587,
User    => 'sender@gmail.com',
Password=> 'Password',
Timeout => 30
);

#  -- Enter email FROM below.   --
$smtp->mail('sender@gmail.com');

#  -- Enter recipient mails addresses below --
my @recipients = ('recipient1@gmail.com', 'recipient2@yahoo.com');
$smtp->recipient(@recipients);
$smtp->bcc(@recipients);

$smtp->data();

#This part creates the SMTP headers you see
$smtp->datasend("To: recipient1\@gmail.com\n");
$smtp->datasend("From: Chandler \n");
$smtp->datasend("Content-Type: text/html \n");
$smtp->datasend("Subject: A Test Mail");
# line break to separate headers from message body
$smtp->datasend("\n");
$smtp->datasend("This is a test mail body");
$smtp->datasend("\n");
$smtp->dataend();

$smtp->quit;

Perl web file download

Reference:
http://jck11.pixnet.net/blog/post/4899927-%E5%88%A9%E7%94%A8lwp%3A%3Asimple%E4%B8%8B%E8%BC%89%E7%B6%B2%E9%A0%81%5Bperl%5D

use LWP::Simple;

my $url = "http://www.otc.org.tw/storage/statistic/financial/O_2013Q2.xls";
my $file = "capital_gretai.xls";
getstore($url, $file);

Perl file unzip

use IO::Uncompress::Unzip qw(unzip $UnzipError) ;

$file_input = 'myfile.zip';
$file_output = 'myfile.xls';

unzip $file_input => $file_output, BinModeOut => 1;