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

Peter Gordon peter at pg-consultants.com
Thu Jun 1 01:29:03 PDT 2006


$sock should work just fine.

if (!socket($sock, PF_INET, SOCK_STREAM, getprotobyname('tcp')))

On Thu, 2006-06-01 at 10:44 +0300, 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, so if 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;
> }
> 




More information about the Perl mailing list