Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl (good practice): lexical filehandle for socket

Tags:

sockets

perl

In perdoc Socket page, they use global filehandle for socket. But if I create a socket in a subroutine called by child processes, is it better to use lexical filehandle still 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 of:

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

It seems to be ok, but I don't know if it's a better practice or completely useless...

Thanks

like image 377
user1334149 Avatar asked May 09 '12 09:05

user1334149


1 Answers

Yes, it's a better practice to use lexical filehandles. But Perl 5.0 didn't have them, so there's plenty of older code and documentation that uses global filehandles, and much of it hasn't been updated to use lexical ones.

P.S. You know that you can say

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

instead of putting the my on the previous line, right?

like image 200
cjm Avatar answered Sep 21 '22 07:09

cjm