develooper Front page | perl.perl5.porters | Postings from June 2020

What am I not grokking about $SIG{__WARN__}?

Thread Next
From:
James E Keenan
Date:
June 30, 2020 13:17
Subject:
What am I not grokking about $SIG{__WARN__}?
Message ID:
671f065f-b0bf-d3fc-3e73-afcc12d673c8@pobox.com
I'm using a stock, unthreaded perl-5.32.0 installed via perlbrew.

#####
$ perl -v | head -2 | tail -1
This is perl 5, version 32, subversion 0 (v5.32.0) built for x86_64-linux
#####

Consider this first file:

#####
$ cat qq1.pl
#!/usr/bin/env perl
use Test::More ( tests => 1 );
is ("\x4i", chr (4) . 'i', '\x4i');
#####

Note that I am *not* running with warnings.  Running this, I get:

#####
$ perl qq1.pl
1..1
ok 1 - \x4i
#####

Now, I activate warnings by adding '-w' to the shebang line.

#####
$ cat qq2.pl
#!/usr/bin/env perl -w
use Test::More ( tests => 1 );
is ("\x4i", chr (4) . 'i', '\x4i');
#####

Running this, I get:

#####
$ perl qq2.pl
1..1
Non-hex character 'i' terminates \x early.  Resolved as "\x04i" at 
qq2.pl line 3.
ok 1 - \x4i
#####

(This warning is expected, given that this program is adapted from 
t/opbasic/qq.t in the core distro, and that file has a comment 
indicating that the test in question will warn.)

Now suppose that I want to capture that warning -- perhaps to compose a 
regex that I would test with Test::More::like() -- and that I am limited 
to code that comes with the core distribution.

Based on past experience and 'perldoc perlvar', I would expect to be 
able to capture the warning with $SIG{__WARN__} and assign it to a 
variable for use in testing.  I would expect the following to DWIM:

#####
$ cat qq3.pl
#!/usr/bin/env perl -w
use Test::More ( tests => 1 );
{
     my $thiswarn = '';
     local $SIG{__WARN__} = sub { $thiswarn = $_[0]; };
     is ("\x4i", chr (4) . 'i', '\x4i');
     print "XXX: thiswarn: $thiswarn\n";
}
#####

But when I run this, the warning is not captured.  Rather, it is emitted 
as in the previous example.

#####
$ perl qq3.pl
1..1
Non-hex character 'i' terminates \x early.  Resolved as "\x04i" at 
qq3.pl line 6.
ok 1 - \x4i
XXX: thiswarn:
#####

What am I not grokking about this?  Why is $SIG{__WARN__} not capturing 
the warning?

Thank you very much.
Jim Keenan

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About