[Israel.pm] socket or file i/o using scalars instead of globs

Scott Weisman sweisman at pobox.com
Thu Jun 1 00:44:38 PDT 2006

Hi there.

I have a sub (pasted below) that takes a TCP port, opens a socket,
sends some data, gets a response, and returns. I use traditional Perl
socket I/O conventions, including a non-declared, non-scalar variable
SOCK. I believe this is referred to as a glob, but I am not sure. In
any case, I need to use a scalar variable instead (eg $sock instead of
SOCK). Can I just change all references in the code to $sock, or do I
need to do more work?

This is one area that has always confused me, so if the answer is
simple, please forgive me for asking.

Thanks for your help,


sub port
    my $port = shift or return;
    my $data = shift;
    my $response;

    if (!socket(SOCK, PF_INET, SOCK_STREAM, getprotobyname('tcp')))
        debug("port: socket error: $!");

    if (!connect(SOCK, sockaddr_in($port, INADDR_LOOPBACK)))
        debug("port: connect error: $!");

    if ($data)
        #setsockopt(SOCK, SOL_SOCKET, SO_LINGER, pack('i2', 1, 16));
        $response = print SOCK $data;
    	#$response = syswrite(SOCK, $data);
        $response = close(SOCK) && $response;
        return $response;

    my ($rv, $rin, $len);

    vec($rin, fileno(SOCK), 1) = 1;

        $rv = select($rin, undef, undef, 10);
        debug("cmf::cf::port: select error: $!") if ($rv < 0);
        last if !$rv;

        $len = sysread(SOCK, $data, 2048);
        $response .= $data;

    } while ($len);

    return $response;

Democracy is two wolves and a lamb voting on what to have for lunch.
Liberty is a well-armed lamb contesting the vote. - Benjamin Franklin

More information about the Perl mailing list