Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

trapping -w warnings

by Anonymous Monk
on Nov 26, 2003 at 06:56 UTC ( #310154=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Dear perl monks: The following code (or something like it) will check the RE in $re for proper syntax. However, -w finds other useful trouble conditions, which it reports to STDERR. I would like to detect these warnings and act on them, and not display them. Can this be done?
#!/usr/bin/perl -w $re = '[\w-]'; eval {'' =~ /$re/ } if($@) {print "error: $@\n"}

Replies are listed 'Best First'.
Re: trapping -w warnings
by Zaxo (Archbishop) on Nov 26, 2003 at 07:08 UTC

    You can set up a $SIG{'__WARN__'} handler. Doing that suppresses printing the message to STDERR. See the perlvar article on %SIG for details.

    After Compline,

      What Zaxo doesn't provide, is a working example. So, here is one, tailored to your snippet:
      $re = '[\w-]'; my @warnings; { local $SIG{__WARN__} = sub { push @warnings, shift }; eval {'' =~ /$re/ }; } if($@) { print "error: $@\n"; } else { foreach my $warning (@warnings) { print "Got a warning: $warning"; } }
      Alternatively, you can do your checking inside the $SIG{__WARN__} sub.

      Note how you need a semicolon after some "blocks" for it to work: after the assignment of the anonymous sub to $SIG{__WARN__}, and after the eval block, at least if any statement comes right after it — which you forgot.

        Perfect. Thanks to both of you. I gather that the effect of "local" as used here is to restore the original handler upon exiting the block?
        I liked this enough that I bookmarked this in my delicious collection -- helped me debug a nasty problem.

        I did things slightly differently though -- more localized, I think.

        { local $SIG{__WARN__} = sub { my @warnings = @_; foreach my $warning (@warnings) { print "got a warning: $warning\n"; } }; eval {'' =~ /$re/ }; }

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://310154]
Approved by idsfa
Front-paged by broquaint
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (2)
As of 2022-05-18 16:40 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (71 votes). Check out past polls.