How do you use select and non-blocking I/O with a short example?

In Perl, you can use the `select` function to work with non-blocking I/O. This allows you to handle multiple filehandles or sockets without waiting for any single one to become ready. Below is an example demonstrating how to set up non-blocking I/O using `select`:

#!/usr/bin/perl use strict; use warnings; # Create a non-blocking socket use IO::Socket; my $sock = IO::Socket::INET->new( PeerAddr => 'localhost', PeerPort => '5000', Proto => 'tcp', Blocking => 0, # Set non-blocking ) or die "Cannot connect: $!\n"; # Set up the filehandle for select my $rin = ''; vec($rin, fileno($sock), 1) = 1; while (1) { my $rout = ''; my $timeout = 5; # seconds my $select_result = select($rout = $rin, undef, undef, $timeout); if ($select_result) { my $data; # Read data if available if (vec($rout, fileno($sock), 1)) { $sock->recv($data, 1024); print "Received: $data\n"; } } else { print "Timeout occurred, no data received.\n"; } }

Perl non-blocking I/O select function socket programming filehandles