试试:: Tiny:捕捉警告的问题

时间:2011-02-26 08:33:35

标签: perl warnings try-catch encode

为什么第二个例子带有“$ encoded = encode($ encoding,$ character,Encode :: FB_WARN | Encode :: LEAVE_SRC);” - 行没有捕获编码警告?

#!/usr/bin/env perl
use warnings;
use 5.012;
use utf8;
binmode STDOUT, ':encoding(utf-8)';
use Encode qw(encode);
use Try::Tiny;

my $character = '€';
my @leer = ( ' ' ) x 4;
my $t = 11;

for my $encoding ( 'iso-8859-1', 'iso-8859-15', 'cp1252', 'cp850' ) {
    my $temp = $character;
    my $encoded;
    my $warning = 'error';
    try {
        $encoded = encode( $encoding, $temp, Encode::FB_CROAK );
    } catch {
        $warning = $1 if m|^\s*(.*\S)\s*at\s/|;
    } finally {
        if ( @_ ) {
            printf "%-${t}s %s:\t%-63s %s\n", $encoding, "encoded", $warning, '--------';
        } else {
            my @a = unpack '(B8)*', $encoded;
            unshift @a, ' ' x 8 while @a < 4;
            printf "%-${t}s %s:\t%8s %8s %8s %8s  %8s %8s %8s %8s\n", $encoding, "encoded", @leer, @a;
        }
    }
}

say "°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°";

for my $encoding ( 'iso-8859-1', 'iso-8859-15', 'cp1252', 'cp850' ) {
    my $encoded;
    my $warning = 'error';
    try {
        $encoded = encode( $encoding, $character, Encode::FB_WARN | Encode::LEAVE_SRC);
    } catch {
        $warning = $1 if m|^\s*(.*\S)\s*at\s/|;
    } finally {
        if ( @_ ) {
            printf "%-${t}s %s:\t%-63s %s\n", $encoding, "encoded", $warning, '--------';
        } else {
            my @a = unpack '(B8)*', $encoded;
            unshift @a, ' ' x 8 while @a < 4;
            printf "%-${t}s %s:\t%8s %8s %8s %8s  %8s %8s %8s %8s\n", $encoding, "encoded", @leer, @a;
        }
    }
}

1 个答案:

答案 0 :(得分:8)

这是因为警告不是例外。但你可以通过

发出警告
use warnings FATAL => 'all';