Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture short host name using built-in Perl modules?

Tags:

perl

Is there a cleaner way to do

use Sys::Hostname qw(hostname);

my $hostname = hostname();
$hostname =~ s/\.domain//;

Basically, is it possible to strip the hostname down to its short name without running two $hostname assignments and without additional modules?

like image 944
theillien Avatar asked Dec 14 '22 23:12

theillien


2 Answers

Using Sys::Hostname:

use Sys::Hostname;

my ($short_hostname) = split /\./, hostname(); # Split by '.', keep the first part

Using system hostname command:

chomp(my ($short_hostname) = `hostname | cut -f 1 -d.`);
like image 110
xxfelixxx Avatar answered Jan 11 '23 09:01

xxfelixxx


You may use Net::Domain's hostname instead

Returns the smallest part of the FQDN which can be used to identify the host.

use Net::Domain qw(hostname);
my $hostname = hostname();

Without additional modules, call external command hostname -s

-s, --short
Display the short host name. This is the host name cut at the first dot.

chomp(my $hostname = `hostname -s`);
like image 24
Olaf Dietsche Avatar answered Jan 11 '23 09:01

Olaf Dietsche