Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

trapping -w warnings

by Anonymous Monk
on Nov 26, 2003 at 06:56 UTC ( [id://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,
    Zaxo

      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/ }; }
        cheers.

Log In?
Username:
Password:

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
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2024-04-19 14:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found