考慮以下這段程式碼:
use JSON;
sub bar { return; }
my $obj = {
k1 => bar(),
k2 => "v2"
};
print JSON::objToJson();
跟據 JSON 的文件,Perl 的 "undef" 這個值,會被它輸出成
"null"。所以,以上這段程式似乎是會有以下的輸出:
{
"k2" : "v2",
"k1" : null
}
但是不然,它的輸出為:
{
"k1" : "k2",
"v2" : null
}
原因在於, bar 函式裡的 "return"
這一句,後面什麼都沒接,印用一下 perldoc
裡的說明:
If no EXPR is given, returns an empty list in list
context, the undefined value in scalar context, and (of course)
nothing at all in a void context.
問題出現於,剛剛呼叫 bar
的語境,便是串列語境,所以它會傳回一個空串列,也就是
()。那在一個串列裡放入空串列,得到的效果,反而會是任何東西都不出現。因為,在串列裡放串列,會被展平
(flattern)。所以,剛剛的程式碼,要不我們就讓 bar
傳回 undef:
sub bar {
return undef;
}
要不,我們們就在做雜湊的時候,強制使用純量語境:
my $obj = {
k1 => scalar bar(),
k2 => "v2"
};
這樣子,才可以確定,那裡一定會擺上一個值。
Cheers,
Kang-min Liu