Perl (good practice): a lexical file descriptor for a socket

In perdoc Socket, the page uses the global file descriptor for the socket. But if I create a socket in a routine called by child processes, is it better to use a lexical file descriptor using Socket?

like this:

use strict; use Socket; sub sendData { my $proto = getprotobyname('tcp'); my $socket; socket($socket, PF_INET, SOCK_STREAM, $proto); ... close($socket) } 

instead:

 sub sendData { my $proto = getprotobyname('tcp'); socket(SOCKET, PF_INET, SOCK_STREAM, $proto); ... close(SOCKET) } 

Everything seems to be in order, but I don’t know if it is better or completely useless ...

thanks

+7
source share
3 answers

Yes, it is better to use lexical file descriptors. But Perl 5.0 did not have them, so there are many old codes and documentation that use global file descriptors, and most of them have not been updated to use lexical ones.

PS you know you can say

 socket(my $socket, PF_INET, SOCK_STREAM, $proto); 

instead of putting my in the previous line, right?

+10
source

Yes, it’s always better to use the lexical area rather than the global one. If you need unique descriptors, albeit global ones, try the Symbol package

+1
source

The Socket module is useful if you need to do some low-level configuration with your socket settings, but for most uses, if not for all purposes, IO::Socket::INET provides a simpler interface. Its constructor returns a socket descriptor as an object, bypassing the need to worry about a global file descriptor.

+1
source

All Articles