因為 UTF-8 有含 BOM 與不含 BOM 的格式,所以如果要處理一個 UTF-8 檔案需要先處理成一致格式再交給程式,以下是最近寫處理申請資料檔案時的相關程式碼.
: : # 檢測 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); : :