2011-03-02 90 views
0

通过“掌握perl”我已经覆盖了“编码”模块的“编码”功能。有没有更简单的方法来使编码 - utf8 - 警告致命?使模块警告致命的最简单方法是什么?

#!/usr/bin/env perl 
use warnings; 
use 5.012; 
binmode STDOUT, ':encoding(utf-8)'; 
BEGIN { 
    use Encode; 
    no warnings 'redefine'; 
    *Encode::encode = sub ($$;$) { 
     my ($name, $string, $check) = @_; 
     return undef unless defined $string; 
     $string .= '' if ref $string; 
     $check ||= 0; 
     unless (defined $name) { 
      require Carp; 
      Carp::croak("Encoding name should not be undef"); 
     } 
     my $enc = find_encoding($name); 
     unless (defined $enc) { 
      require Carp; 
      Carp::croak("Unknown encoding '$name'"); 
     } 
     use warnings FATAL => 'utf8'; ### 
     my $octets = $enc->encode($string, $check); 
     $_[1] = $string if $check and !ref $check and !($check & LEAVE_SRC()); 
     return $octets; 
    } 
} 

use Encode qw(encode); 
use warnings FATAL => 'utf8'; 

my $character; 
{ 
    no warnings 'utf8'; 
    $character = "\x{ffff}"; 
# $character = "\x{263a}"; 
} 

my $utf32; 
eval { $utf32 = encode('utf-32', $character) }; 
if ([email protected]) { 
    (my $error_message = [email protected]) =~ s/\K\sin\ssubroutine.*$//; 
    chomp $error_message; # where does the newline come from? 
    say $error_message; 
} 
else { 
    my @a = unpack('(B8)*', $utf32); 
    printf "utf-32 encoded:\t%8s %8s %8s %8s %8s %8s %8s %8s\n", @a; 
} 

subquestion:s ///之后的$ error_message中的换行符来自哪里?

回答

3

我不确定我是否按照您的主要问题... use warnings FATAL => 'utf8';已经很短了;我认为你不可能找到更短的东西。

对于subquestion,.在一个正则表达式将默认,匹配任何字符换行符以外,使替代不排除最终换行符:

$ perl -e '$foo = "foo bar baz\n"; $foo =~ s/bar.*$//; print $foo . "---\n";' 

打印

foo 
--- 

要获得.以匹配换行符,请将/s修饰符添加到您的正则表达式中:

perl -e '$foo = "foo bar baz\n"; $foo =~ s/bar.*$//s; print $foo . "---\n";' 

打印

foo --- 
+0

我必须覆盖编码功能,使UTF8的警告致命? – 2011-03-02 10:12:35

+0

@sid_com:是的,如果你打算通过使用警告FATAL来做到这一点,因为'使用警告'是词法范围的,并且不会影响另一个文件中的代码。但是,您可以从$ SIG {__ WARN__} = sub {die @_; };然后添加一个条件,以便它只会在UTF-8错误上死掉 - 但是您可能必须通过检查错误信息来检测它们,这些信息充满了龙。 – 2011-03-02 11:19:01

相关问题