Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: trapping -w warnings

by Zaxo (Archbishop)
on Nov 26, 2003 at 07:08 UTC ( [id://310158]=note: print w/replies, xml ) Need Help??


in reply to trapping -w warnings

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

Replies are listed 'Best First'.
Re: Re: trapping -w warnings
by bart (Canon) on Nov 26, 2003 at 07:24 UTC
    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?
        Yup.
      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.
        AFAIK $SIG{__WARN__} is only ever called with one parameter: the current warning. So your loop is most likely useless.

        You can print each warning as it comes along. But what I did was collect the warnings first so you can print them out as a block. That may be useful if you want just one block, for example when printing warnings in a HTML page on a web server.

        On second thought, I don't think I needed that eval block. This works fine too.
        use strict; use warnings; { local $SIG{__WARN__} = sub { my @warnings = @_; foreach my $warning (@warnings) { warn "in handleEncoding, got a warning: $warning\n"; } }; warn "blee"; warn "blah"; warn "bloo"; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://310158]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2024-04-25 22:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found