Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try::Tiny: Problem with catching warnings

Why does the second example with the "$encoded = encode( $encoding, $character, Encode::FB_WARN | Encode::LEAVE_SRC);"-line not catch the encode-warnings?

#!/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;
        }
    }
}
like image 818
sid_com Avatar asked Mar 03 '26 11:03

sid_com


1 Answers

It is because warning is not an exception. But you can make warnings throw exception by

use warnings FATAL => 'all';
like image 51
bvr Avatar answered Mar 05 '26 01:03

bvr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!