Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most elegant way to catch a signal in Perl?

I have 2 lines near one another in a Perl script that could throw a __WARN__. If the first one throws, then I want to just return from the function and not try to continue.

I know how to set up a handler before both lines so I can report the error etc:

local $SIG{__WARN__} = sub {
  my $e = shift;
  # log the error etc.
  return;
};
# possibly warning-resulting line 1
# possibly warning-resulting line 2

But then this happens for both lines. I'd rather it just caught the first instance and returned from the function. But the return in that handler only returns the handler, not the outer function.

Is there a way to return from the function when handling a signal?

like image 654
John Bachir Avatar asked Dec 19 '25 22:12

John Bachir


1 Answers

Wrap the two lines in separate functions, and have the first return a status indicating that the calling function should return. The separate functions can deal with the warnings as you need - possibly using the same function to do the same logging.

sub wrap_line_1
{
    local $SIG{__WARN__} = ...;
    ...do line 1...
    return ($warning_fired ? 1 : 0);
}

sub wrap_line_2
{
    local $SIG{__WARN__} = ...;
    ...do line 2...
    return;
}


...calling code...
wrap_line_1() and return;
wrap_line_2();
...
like image 136
Jonathan Leffler Avatar answered Dec 22 '25 20:12

Jonathan Leffler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!