2008年12月4日

find the colors of your rainbow

Your rainbow is shaded violet.

 
 
 
 
 
 
 

What is says about you: You are a creative person. You appreciate beauty and craftsmanship. You are patient and will keep trying to understand something until you've mastered it.

Find the colors of your rainbow at spacefem.com.

心理測試之類的東西...可以玩玩

2008年12月3日

Perl的XML Parser XML::Simple (2)

來寫XML::Simple 裡面 XMLout跟一些Option的設定. 最後面附的example寫的到的話再說...
照樣附上原文 <--直接reference到XMLout
假設已經有一個data structure的hashref了, XMLout可以將它寫出成XML格式.
寫出的時候有一些事情必須注意; 1. Hash Key會被encode成element name or Attribute name.
2. 這些name必須由字母開頭. 剩下的必須為字母, 數字, -, 底線, '.', 或者分號(這個只能出現一次, 而且必須被用於namespaces). hash value部分就可以隨便用符號, 除了binary data以外.
如果違反這些規則, XMLout還是可以寫出, 只是不能再被讀取而已.
另外資料還是不要有產生迴圈的關係, 會讓他掛掉.

Options:
每一版他都會release一些新的option, 所以其實這個XML::Simple已經變得不是很簡單了:) 作者建議兩個Option一定要看一下: ForceArray, KeyAttr

挑一些簡單, 作者建議的Option來看:
AttrIndent=>1: 輸出的時候請斷行.
ForceArray=>: 設成1的時候將會將巢狀結構的第二層開始都強制存成array, 不管他是不是只有一項. 若把KeyAttr打開的時候, 將會偷偷把ForceArray設為1.
或者可以給一個hashname, 這樣遇到該hashname的時候會自動強制存成array. 2.05版開始可以用regular expression.
KeepRoot=>1: 有時候讀入或讀出會遺失root, 這個option設為1會避免這個狀況.
KeyAttr=>[list]: 還滿難講的....附上原文的例子比較清楚.
NoAttr=>1: 把所有Attribute去掉.
OutputFile=>: 可以指定output file.

Optional OO Interface; 就是專門給OO使用的.
要先有一個new出來的XML::Simple的instance.
parse_string(text)
parse_file(filename)
parse_fh(file_handle)

看完了, 其實很多option都是幫忙整理XML讀進來的format, 讓找值的時候code不會太難看....
似乎有進階用法, 之後再看看好了.

Perl的XML Parser XML::Simple (1)

工作上會用到有關XML的東西, 講到資料處理當然是Perl啦, 馬上來survey一下.

cpan提供了一些好用的module, XML::Simple基本上灌完ActivePerl就有內建. 此Module的作者首頁
下面大量翻譯網頁裡的東西, 有興趣可以看看原文.
XML::Simple是一個Perl Module, 主要為了提供一個容易讀寫XML文件的界面. 本來作者是想做一個讀寫XML格式的config檔案. 不過很多人拿去做其他用途(kerker.

Installation:
上面提到很多安裝的方法, 包括用cpan提供的shell啊, 安裝檔啊..不過作者說只要把Simple.pm解壓縮出來放到perl/lib/XML/底下就可以了:)

用法: (原文)

主要使用的function: XMLin; XMLout

一般 format:
use XML::Simple;

my $ref = XMLin([] [, ]);

my $xml = XMLout($hashref [, ]);
用物件導向讓你看不懂的話:
require XML::Simple;

my $xs = XML::Simple->new(options);

my $ref = $xs->XMLin([] [, ]);

my $xml = $xs->XMLout($hashref [, ]);
如果要得到error message, 只要作一些修改
use XML::Simple qw(:strict);

一個簡單的範例:
file name :foo.xml
XML包法:

裡面項目可大量.

perl 程式裡:
use XML::Simple;

my $config = XMLin();

這會產生一個名叫$config的hashref, 因為他沒有設定初值, $config會預設對應到該Script的name跟location.

接下來要將資料吃進來, 使用Data::Dumper把資料弄進去:
use Data::Dumper;

print Dumper($config);
印出來會有如下效果:
{
'logdir' => '/var/log/foo/',
'debugfile' => '/tmp/foo.debug',
'server' => {
'sahara' => {
'osversion' => '2.6',
'osname' => 'solaris',
'address' => [ '10.0.0.101', '10.0.1.101' ]
},
'gobi' => {
'osversion' => '6.5',
'osname' => 'irix',
'address' => '10.0.0.102'
},
'kalahari' => {
'osversion' => '2.0.34',
'osname' => 'linux',
'address' => [ '10.0.0.103', '10.0.1.103' ]
}
}
}
這是hashref裡面包的內容, 記得他是一個物件.
那要怎麼拿裡面的元素呢? 假設我要拿log directory的name
print $config->{logdir};
如果要拿特定的元素, 例如 kalahari Server的第二個Address
print $config->{server}->{kalahari}->{address}->[1];

但程式不會只寫的這麼簡單. 下回待續?