How to timeout and proceed in perl?

I'm writing a small socket program (UDP) to communicate between two servers.
Problem is, I dont know how to implement time out hence my script keeps on waiting for the peer response.

#!/usr/bin/bash
use IO::Socket::INET;
$|=1;
$socket=new IO::Socket::INET->new(LocalPort=>5001,
						    Proto=>'udp',
						    timeout=>5);
print "\nUDPServer Waiting for client on port 5001 and will timeout in 5 secs";
$socket->recv($recieved_data,1024);
print "\nReceived data $recieved_data \n \n";

Here if there is no message received the script keeps on waiting forever..

I couldnt understand the use of timeout here (i guess its for udp). Googling for this issue redirects me to select() and alarms, where im stuck with my little knowledge in perl.

Perl: How to get IO::Socket::INET timeout after X seconds? - Stack Overflow

1 Like

Thanks itkamaraj. It worked. Here is the code..

#!/usr/bin/perl
use IO::Socket::INET;
$|=1;
$socket=new IO::Socket::INET->new(LocalPort=>5001, Proto=>'udp');
print "\nUDPServer Waiting for client on port 5001 and will timeout in 5 secs";
eval {
  local $SIG{ALRM} = sub { die 'Timed Out'; };
  alarm 5;
  $socket->recv($recieved_data,1024);
  print "\nReceived data $recieved_data \n \n";
    alarm 0;
};
alarm 0;
print "\nError: timeout \n" if ( $@ && $@ =~ /Timed Out/ );