【问题标题】:What is the simplest way to make modules warnings fatal?使模块警告致命的最简单方法是什么?
【发布时间】:2011-03-02 08:12:38
【问题描述】:

通过“掌握 perl”,我覆盖了“编码”模块的“编码”功能。是否有更短的方法可以使 encode-utf8-warnings 致命?

#!/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 ( $@ ) { 
    ( my $error_message = $@ ) =~ 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;
}

子问题:$error_message 中 s/// 后面的换行符是从哪里来的?

【问题讨论】:

    标签: perl warnings perl-module overwrite


    【解决方案1】:

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

    至于子问题,正则表达式中的. 默认匹配任何字符除了换行符,因此替换不会删除最后的换行符:

    $ 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 ---
    

    【讨论】:

    • 我是否必须覆盖编码函数才能使 utf8 警告致命?
    • @sid_com: 是的,你会这样做,如果你将通过use warnings FATAL 来做,因为use warnings 是词法范围的并且不会永远 影响另一个文件中的代码。但是,您可以从 $SIG{__WARN__} = sub { die @_; }; 开始,然后添加一个条件,以便它只会在 UTF-8 错误时死掉 - 但您可能必须通过检查错误消息来检测它们,其中充满了龙。跨度>
    猜你喜欢
    • 2016-03-20
    • 2010-09-09
    • 2019-04-01
    • 2013-04-06
    • 2018-07-04
    • 1970-01-01
    • 2015-03-01
    • 2022-02-04
    相关资源
    最近更新 更多