Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Perl处理格式错误的字符_Perl_Encoding - Fatal编程技术网

Perl处理格式错误的字符

Perl处理格式错误的字符,perl,encoding,Perl,Encoding,我想听听关于Perl的建议 我想用Perl处理一些文本文件。这些文本文件用cp932编码,但由于某些原因,它们可能包含格式错误的字符 我的计划是: #! /usr/bin/perl -w use strict; use encoding 'utf-8'; # 'workfile.txt' is supposed to be encoded in cp932 open my $in, "<:encoding(cp932)", "./workfile.txt"; while ( my $

我想听听关于Perl的建议

我想用Perl处理一些文本文件。这些文本文件用cp932编码,但由于某些原因,它们可能包含格式错误的字符

我的计划是:

#! /usr/bin/perl -w

use strict;
use encoding 'utf-8';

# 'workfile.txt' is supposed to be encoded in cp932
open my $in, "<:encoding(cp932)", "./workfile.txt";

while ( my $line = <$in> ) {

  # my process comes here

  print $line;

}
如果workfile.txt包含格式错误的字符,Perl会抱怨:

cp932 "\x81" does not map to Unicode at ./my_program.pl line 8, <$in> line 1234.
Perl知道其输入是否包含格式错误的字符。所以我想重写,看看我的输入是好是坏,并相应地采取行动,比如说,将所有不包含格式错误字符的行打印到输出文件句柄A,并将包含格式错误字符的行打印到输出文件句柄B

#! /usr/bin/perl -w

use strict;
use encoding 'utf-8';
use English;

# 'workfile.txt' is supposed to be encoded in cp932
open my $in, "<:encoding(cp932)", "./workfile.txt";

open my $output_good, ">:encoding(utf8)", "good.txt";
open my $output_bad,  ">:encoding(utf8)", "bad.txt";

select $output_good;   # in most cases workfile.txt lines are good

while ( my $line = <$in> ) {

  if ( $line contains malformed characters ) {

    select $output_bad;

  }

  print "$INPUT_LINE_NUMBER: $line";

  select $output_good;

}
我的问题是,如果$line包含错误的字符,我如何编写此代码。如何检查输入是否正确


提前感谢。

不要使用编码。婴儿车。不推荐使用。ikegami san,非常感谢!我将使用eval查看是否存在格式错误的字符。阿里加托!我写这篇文章的时候没有看cp932是什么。但我知道这是一种多字节编码。这意味着我的$line=可能无法正常工作。ikegami,我不太聪明,不会想到我的$line=出现中断的情况,但我很高兴地报告,我使用eval技术的程序可以完美地检测所有格式错误的数据。非常感谢你!请注意,这在某些情况下可能不起作用。如果0A可以是换行符以外的字符的一部分,则会出现问题。我不知道这是否可行。池上,再次谢谢。格式错误的数据可能包含0A,但到目前为止还不错。我注意到从文件句柄读取行可能会中断。
#! /usr/bin/perl -w

use strict;

use utf8;                             # Source encoded using UTF-8
use open ':std', ':encoding(UTF-8)';  # STD* is UTF-8;
                                      #   UTF-8 is default encoding for open.
use Encode qw( decode );

open my $fh_in,   "<:raw", "workfile.txt"
   or die $!;
open my $fh_good, ">",     "good.txt"
   or die $!;
open my $fh_bad,  ">:raw", "bad.txt"
   or die $!;

while ( my $line = <$fh_in> ) {
   my $decoded_line =
      eval { decode('cp932', $line, Encode::FB_CROAK|Encode::LEAVE_SRC) };
   if (defined($decoded_line)) {
      print($fh_good "$. $decoded_line");
   } else {
      print($fh_bad  "$. $line");
   }
}