Nov 272012
Article Perl

The “alarm” function available in perl triggers the execution of a subroutine after a specified time has elapsed.

Making use of this function, it is possible to implement a function that asks the user to type some input, and times out if no answer has been received after a given time, continuing the execution of the script.

The function can be implemented using this code

We can see in the example above that, inside an eval block:

  • A subroutine that just calls “die()” is assigned as the alarm handler. Being inside an eval block, this call does not finalize the script. Instead, it raises an exception that is handled in the sentence “if ($@)”.
  • After the alarm has been set up to trigger in five seconds, the script keeps waiting for input from the keyboard.
  • If data is received, the sentence “alarm 0” disables the alarm.

With this code, if the user has not entered data in five seconds, the routine that calls die() is executed, and the script leaves the eval block. Then the value in the variable¬†$@ is checked to confirm that it matches the “timeout reading from keyboard” message specified in the call to die():

– If it does not match, some other type of error has happened.

– If it matches, the variable $answer is assigned the value “No answer given”.

Finally, the script leaves the “ask_data” subroutine, returning the value in the variable $answer.

 Posted by at 9:15 pm

 Leave a Reply