Our second method is connect. Yes, that name is overused, but it describes exactly what we are doing even if we also have to use the built-in “connect” method that is part of the TCP/IP functions in Perl (and the underlying C library). Ours will be part of the Astro::INDI object we are creating, so there will be no conflict.  We’ll also supply disconnect for symmetry, and supply a synonym close.

# Method to connect to indiserver
sub connect {
my ($self, %initializer) = @_;
foreach my $key (keys %initializer) {
$self->{$key} = $initializer{$key};
}

my $iaddr = inet_aton($self->{host})
or die("unknown host $self->{host}");
my $paddr = sockaddr_in($self->{port}, $iaddr);
my $proto = getprotobyname('tcp');
my $sock;
socket($sock, PF_INET, SOCK_STREAM, $proto)
or die("socket: $!");
connect($sock, $paddr)
or die("connect: $!");
$self->{sock} = $sock;
}

# Method to disconnect
sub disconnect {
my $self = shift;
close($self->{sock});
}

# Alias for disconnect
sub close {
my $self = shift;
$self->disconnect(@_);
}

There’s nothing particularly special here; this is really just more boilerplate for anything that uses TCP/IP.  The only real comment here about keeping in mind error handling and testing.