Lines 1 “9: Load modules and process command-line arguments We turn on strict type checking and load the IO::Select and IO::Socket modules. We read the host and port to connect to from the command line, or if a host is not specified, we assume the echo service on the local host.
Line 10: Create a new connected socket We create a socket connected to the specified peer by calling IO::Socket::INET->new() with the one-argument shortcut form.
Lines 11 “13: Create a new IO::Select set We will multiplex our reads on standard input and on the socket. This means that we will read from standard input only when the user has some data for us and read from the socket only when there's server data to be read.
To do this, we create a new IO::Select object by calling IO::Select->new() . An IO::Select object holds one or more filehandles that can be monitored for their readiness to do I/O. After creating the select object, we add STDIN and the socket by calling the select object's add() method.
Lines 14 “17: Main I/O loop We now enter a while() loop. Each time through, we call the select object's can_read() method to return the list of handles ready for reading. This list may contain the socket handle, STDIN , or both. Our task is to loop through the list of ready handles and take the appropriate action for each. If STDIN is ready for reading, we copy data from it to the socket. If the socket is ready, we copy data from it to STDOUT .
Lines 18 “24: Handle data on STDIN If STDIN is ready to be read, we use sysread () to read up to 2K bytes of data into a string variable named $buffer . If sysread() returns a positive value, we write a copy of what we received to the socket. Otherwise, we have encountered an end of file on standard input. We shutdown() the write half of the socket, sending the remote server an end of file.
Lines 25 “32: Handle data on the socket If there is data to be read from the connected socket, then we call sysread() on the socket to read up to 2K bytes. If the read is successful, we immediately print it to STDOUT . Otherwise, the remote host has closed the connection, so we write a message to that effect and exit.