Perl get user input with timeout


/ Published in: Perl
Save to your folder(s)

Author: jsinix([email protected])

This is a script that demonstrates how to get input from keyboard with a timeout. This can be useful in many places.


Copy this code and paste it in your HTML
  1. #!/usr/bin/perl
  2. # This is a script that demonstrates
  3. # how to get input from keyboard
  4. # with a timeout. This can be useful
  5. # in many places.
  6.  
  7. use strict;
  8. use warnings;
  9.  
  10. sub ask_data {
  11. my ($tout) = @_;
  12. my $answer;
  13.  
  14. print "Enter the data before $tout seconds: ";
  15. eval {
  16. local $SIG{ALRM} = sub { die "timeout reading from keyboard" };
  17. alarm $tout;
  18. $answer = <STDIN>;
  19. alarm 0;
  20. chomp $answer;
  21. };
  22. if ($@) {
  23. die $@ if $@ ne "timeout reading from keyboard";
  24. $answer = 'No answer given';
  25. }
  26. return $answer;
  27. }
  28.  
  29. my $data = ask_data('10');
  30. print "\nThe answer is: " . $data . "n";

URL: www.jsinix.com

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.