Perl Retry on alarm

I am trying to retry certain logic when an alarm is triggered. Is that possible. I have defined the alarm as below:

local $SIG{ALRM} = sub {
         if($attempt <=5) {
              print "NExt attempt\n";
              $attempt = $attempt + 1;
              my $val = subroutine_call();
         } else{
         Carp::confess "Die now\n"; 
         }

My code snippet is as below:

 foreach my $x (@array)
 {
     eval {
        alarm(2);
        my $val = subroutine_call();
        alarm(0);
     };

     print "Moving on \n";
     ## some code
  }

I wish to retry calling the subroutine_call upto 3 times when the alarm is triggered before terminating the application. After calling the subrountine_call(irrespective of whether it was called after alarm got triggered or not), it should display print statement.

I know that the code flow would deviate once the alarm is triggered and subrountine_call is made through the alarm definition and it would not execute the print statement. I want it to behave as if it would have if alarm would not hadn't gotten triggered.

Is that possible? I am skeptical but wanted to know if it is so.

Thanks,

Answers


local $SIG{ALRM} = sub { die "alarm\n"; };

for my $x (@array) {
   my $attempts_remaining = 3;
   while (1) {
      last if eval {
         alarm(2);
         subroutine_call();
         alarm(0);
         return 1;
      };

      my $e = $@;
      die($e) if $e ne "alarm\n";
      die("Timeout!\n") if !--$attempts_remaining;
      warn("Timeout! Trying again...\n");
   }
}

Need Your Help