2009年6月21日

Perl Module PAR::Packer 筆記 perl convert to exe

要把perl打包成可執行檔有三種方法:
PAR::Packer, perl2exe, ActiveState的Perl Dev kit
但perl2exe與Perl Dev Kit屬商業軟體,有使用限制(試用版也有時間的限制),所以我選擇使用PAR來打包成執行檔,當然商業軟體有他的優點,若有需要還是請到閱讀官網所提供的資訊。


於Windows環境安裝PAR::Packer

windows環境的大多都是用ActiveState的ActivePerl,這裡有一份PAR PPM的相容列表,請先查閱你所安裝的ActivePerl是否相容。

由於ActiveStat的repository並沒有提供PAR::Packer,所以要另外安裝bribes這個repository。

請開啟一個「命令提示字元」並執行
ppm repo add http://www.bribes.org/perl/ppm bribes



安裝PAR::Packer
ppm install PAR-Packer

再來把我寫好的perl script打包成可獨立執行的程式。使用的方法很簡單,執行如下指令
pp -o find.exe find.pl



當然PAR::Packer的功能當然沒這麼少,詳細的功能請參閱CPAN上的文件

2009年6月18日

用 perl 列出指定目錄下的檔案及目錄

update on 2012/1/14

方法一:
Find::Find 是 perl 內含的模組,他可以列出指定目錄下的檔案及目錄
#!/usr/bin/perl -w

use strict;
use File::Find;

find( \&wanted, "/etc");
sub wanted() {
#列出目錄
print $File::Find::dir . "\n";

#列出檔案
print $_ . "\n";

#列出檔案的絕對路徑
print $File::Find::name . "\n";
}


利用匿名 hash 設定 File::Find 的參數
這邊特別提到 no_chdir 參數,讓 File::Find 不要切換工作目錄,如此 $_ 的內容等同 於$File::Find::name

#!/usr/bin/perl -w

use File::Find;
use strict;

#啟用 no_chdir 參數,各位可以比對一下確實與 $File::Find::name 內容相同
find( { wanted => \&wanted, no_chdir => 1}, "/etc" );
sub wanted() {
print $_ . "\n";
}
#利用匿名函式將找到的目錄存到陣列
#!/usr/bin/perl -w

use strict;
use File::Find;

my @FileList;
find( { wanted => sub { push(@FileList, $_) }, no_chdir => 1 }, "/etc" );



方法二:
File::Next是另一個遊走整個目錄樹以取得檔案或目錄列表的模組,可惜這個模組需要另外安裝,使用上比較不方便
http://search.cpan.org/dist/File-Next-1.02/Next.pm
#取得檔案列表
#!/usr/bin/perl -w

use strict;
use File::Next;

my $iter = File::Next::files( '/tmp' );

while ( defined ( my $file = $iter->() ) ) {
print $file, "\n";
}

執行後得到
/tmp/file1
/tmp/file2
/tmp/a/file1
..

※若要取得目錄只要將File::Next::files改為File::Next::dirs
※若要取得所有的檔案、目錄 or whatever 就改為File::Next::everything

#搜尋檔案(同linux下的find指令)
#紅字部份為過濾條件,也就是你想找的檔案名稱。下面的程式會找出gd.txt的路徑
my $iter = File::Next::files( {file_filter => sub { /gd\.txt$/ } }, 'D:\\' );
while ( defined ( my $files = $iter->() ) ) {
print $files, "\n";
}