IO Objects and Filehandles

Perl supports the BSD socket call, which returns a filehandle, as open does for files and pipes. This filehandle can be used as an argument for all the built-in input-output operators: <> , read, sysread, print, write, syswrite , and so on. In addition, it can be used by socket-specific functions such as send, recv, and setsockopt.

The IO::Socket module’s new method returns an object that can also be used as a parameter to these I/O routines. Internally, it calls socket and uses the typeglob corresponding to the filehandle to store other attributes; we described this hideous-looking trick in Chapter 8, in the section Section 8.1. In other words, its return value is the same object that was given to socket, which is why it does not matter to the I/O operators which option you choose. My recommendation is to go for the considerably easier to use IO::Socket option.

IO::Select is another story, however. If performance is absolutely crucial, you may prefer to do yourself what IO::Select implements:

$r_bitset = $w_bitset = $e_bitset = '';
# Monitor $sock1 for reading
vec($r_bitset, $sock1->fileno(), 1) = 1;
# Monitor $sock2 for writing
vec($w_bitset, $sock2->fileno(), 1) = 1;
# Monitor both for errors
$e_bitset = $r_bitset | $w_bitset;

($nfound, $timeleft) = 
    select ($r_bitset, $w_bitset, $e_bitset, $timeout);

The native select function requires three bit vectors representing collections of open files, sockets, or pipes. Each bit in these bit sets corresponds ...

Get Advanced Perl Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.