====== Perl + Linux 檢測檔案是否為 UTF-8 與去除 BOM 方式 ======
因為 UTF-8 有含 BOM 與不含 BOM 的格式,所以如果要處理一個 UTF-8 檔案需要先處理成一致格式再交給程式,以下是最近寫處理申請資料檔案時的相關程式碼.
* 判別是否為 UTF-8 檔案主要是採用 Linux 內的 file 指令
* 判別是否含有 BOM 的 UTF-8 是取檔案前兩個字元判別是否為 #0xef -> 239 / #0xbb -> 187,如果是就去掉.
:
:
# 檢測 csv 是否為 UTF-8 格式
$t_msg = `/usr/bin/file $p_regdir$p_csvfile`;
if (index($t_msg, "UTF-8")<0) {
$hash_logXMLInfo{'note'}="CSV File encoding is not UTF-8!";
return((-1, "CSV File info:[$t_msg]", %hash_logXMLInfo));
}
$v_csvInfo = `/bin/cat $p_regdir$p_csvfile`;
# 如果 csv 有函 BOM 的 UTF-8 則去掉前兩碼
$t_chk1 = substr($v_csvInfo, 0, 1); #0xef -> 239
$t_chk2 = substr($v_csvInfo, 1, 1); #0xbb -> 187
if (ord($t_chk1)==239 && ord($t_chk2)==187) {
$v_csvInfo = substr($v_csvInfo, 3);
}
# 讀取 csv 檔案內容 (支援 Unix \n 與 Dos \r\n 換行格式)
@arr_csvLine = split(/\n|\r\n/,$v_csvInfo);
:
:
進一步可以將這樣的概念弄成一個 function 出來, 先將檔案讀入成字串, 然後傳入給這個 removeBOM 判別移除傳回.
# 21:28 2008/12/15
# 如果有 UTF-8 BOM 就去除掉
sub removeBOM {
local($p_content) = @_;
if (ord(substr($p_content,0,1))==239 && ord(substr($p_content,1,1))==187) {
return(substr($p_content,3));
}
return($p_content);
}
{{tag>perl utf8 BOM 密技}}