http://qs321.pair.com?node_id=681992

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

Greetings,
 Im using Cache::Memcached in my script. The following call to stats() will throw warnings if the memcached server is not running:
use warnings; use Cache::Memcached; my $memd = new Cache::Memcached {servers => ["$host:$port"]}; my $stats = $memd->stats();
  I want to trap such warnings as errors (so I can eval/die in my code), hence I tried this in my code:
use warnings FATAL => 'all';
Since, the above pragma will not "leak across files" according to perllexwarn, Im forced to do this:
$SIG{'__WARN__'} = sub { die $_[0]};
not that anything is wrong with setting up signal handlers, I want to know if I can somehow use the warnings pragma to achieve the same. Thanks.

Replies are listed 'Best First'.
Re: Cache::Memcached and converting warnings to fatal
by mscharrer (Hermit) on Apr 21, 2008 at 19:50 UTC
    AFIK you can't use the warnings pragma to achieve the same, because its, as you already said, doesn't effect other scopes. Even the funny idea to do
    # Inside your script: package Cache::Memcached; use warnings FATAL => 'all'; package main; [...]
    would help :-)

    Just use the handler. This is also mentioned in the perldoc page of eval. Please don't forget to use the local statement to make the handler local to your closure:

    my $stats = eval { local $SIG{'__WARN__'} = sub { die }; $memd->stats(); } if ($@) { # No stats!! [...] }
    I also would remove the argument to die as long you don't want the warning message, which is now the error message, printed. Normally you do a warn $@ if $@ or similar.
Re: Cache::Memcached and converting warnings to fatal
by Narveson (Chaplain) on Apr 21, 2008 at 21:05 UTC
    I want to trap such warnings as errors (so I can eval/die in my code)

    What is the return value from stats() when the warning is thrown? Is it logically false?

    If so, you can say

    use Fatal qw(Cache::Memcached::stats);

    Of course, if this works, you can equally well say

    my $stats = $memd->stats() or die;

    and since you aren't doing that, I guess your failed stats() calls have been returning true values.

    I would file a bug report.

Re: Cache::Memcached and converting warnings to fatal
by rhesa (Vicar) on Apr 21, 2008 at 21:40 UTC
    This doesn't scale when you add more memcached nodes. Just because one node is down, doesn't mean you won't get stats for the other ones. I just ignore the warnings (although it is noisy).