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

guy keren choo at actcom.co.il
Thu Jun 1 06:04:14 PDT 2006


why don't you just use the perl modules that wrap up sockets, and have an
easier interface?

i think it's IO::Socket - i used this in some perl scripts of mine, and it
worked on 4 flavors of unix and on windows too.

--guy

On Thu, 1 Jun 2006, Scott Weisman wrote:

> 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, soif the answer is
> simple, please forgive me for asking.
>
> Thanks for your help,
>
> Scott
>
> 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: $!");
>       return;
>   }
>
>   if (!connect(SOCK, sockaddr_in($port, INADDR_LOOPBACK)))
>   {
>       debug("port: connect error: $!");
>       return;
>   }
>
>   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;
>
>   do
>   {
>       $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);
>
>   close(SOCK);
>   return $response;
> }
>
>

-- 
guy

"For world domination - press 1,
 or dial 0, and please hold, for the creator." -- nob o. dy



More information about the Perl mailing list