2011-03-02 89 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

相關問題