簡體   English   中英

Perl 用 UTF-8 BOM 格式讀取.DAT 文件並用 UTF-8 格式寫入不帶 BOM

[英]Perl read .DAT file with UTF-8 BOM format and write it with UTF-8 format without BOM

我有一個帶有 CR LF 和 UTF-8 格式的帶有 BOM 的.DAT 文件,我正在嘗試使用 Z0114AD06D728F1834E36FE1A39574EF4 將其轉換為沒有 BOM 的 CR LF UTF-8 格式我目前正在使用以下代碼來執行此操作,盡管 output 文件是在沒有 BOM 的情況下生成的,但 header 不包含在數據的 Z65E8800B5C6800AAD896F888B2A6AFC 文件中。 我的要求是獲得 UTF-8 格式的最終 output 文件,沒有 BOM 和 header 包含在 Z65E8800B8CDB2006 的數據中。

use open qw( :encoding(UTF-8) :std ); # Make UTF-8 default encoding

sub encodeWithoutBOM
{
    my $src = $_[1];
    my $des = $_[2];
    my @array;
    open(SRC,'<',$src) or die $!;
    # open destination file for writing
    open(DES,'>',$des) or die $!;
    print("copying content from $src to $des\n");
    while(<SRC>){
         @array = <SRC>;    
    }
    foreach (@array){
    print DES;
    }
    close(SRC);
    close(DES); 
} 
use open ':std', ':encoding(UTF-8)';

while (<>) {
   s/^\N{BOM}// if $. == 1;
   print;
}

另一種選擇是使用 CPAN 中的File::BOM ,它可以讓您透明地處理字節順序標記:

#!/usr/bin/env perl
use warnings;
use strict;
use autodie;
use feature qw/say/;
use File::BOM qw/open_bom/;

sub encode_without_bom {
    my ($src, $dst) = @_;

    open_bom(my $infile, $src, ":encoding(UTF-8)");
    open my $outfile, ">:utf8", $dst;
    say "Copying from $src to $dst";
    while (<$infile>) {
        print $outfile $_;
    }
}

encode_without_bom "input.txt", "output.txt";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM