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";
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?