What is the most elegant way to catch a signal to 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.
# 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?

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...

...calling code...
wrap_line_1() and return;