繁体   English   中英

使模块警告致命的最简单方法是什么?

[英]What is the simplest way to make modules warnings fatal?

通过“掌握perl”,我已经覆盖了“编码”模块的“编码”功能。 有没有一种较短的方法可以使encoded-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;
}

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

我不确定我是否遵循您的主要问题... 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 ---

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM