Perl Stop Print If Error Wide Characters

I have a simple print script

my $pdf_data = $agent->content;
open my $ofh, '>:raw', "test.pdf"
or die "Could not write: $!";
print {$ofh} $pdf_data;
close $ofh;

Sometimes I get a "Wide Symbol Alert", I know why I get it, and would like to be able to cancel printing instead of printing a damaged failure. Sort of

if(wideCharWarning)
{
delete "test.pdf"
}
else{
print {$ofh} $pdf_data;
}
+3
source share
3 answers

You indicated that you are printing bytes (: raw), but that is not the case.

$ perl -we'
   open(my $fh, ">:raw", "file") or die $!;
   for (0..258) {
      print "$_\n";
      print $fh chr($_);
   }
'
...
249
250
251
252
253
254
255
256
Wide character in print at -e line 5.
257
Wide character in print at -e line 5.
258
Wide character in print at -e line 5.

To “cancel printing”, you just need to check that what you print does not contain bytes.

die if $to_print =~ /[^\x00-\xFF]/;
+4
source

If you want to determine if your string contains wide characters, you can use a regex:

/[^\x00-\xFF]/;

(as shown below, my first sentence was out of order: it /[^[:ascii:]]/;would generate false positives)

+5
source

You can install a signal handler __WARN__and do whatever you want based on a warning message.

my $wideCharWarningsIssued = 0;
$SIG{__WARN__} = sub {
    $wideCharWarningsIssued += "@_" =~ /Wide character in .../;
    CORE::warn(@_);     # call the builtin warn as usual
};

print {$ofh} $data;
if ($wideCharWarningsIssued) {
    print "Never mind\n";
    close $ofh;
    unlink "test.pdf";
}
+1
source