theillien
theillien

Reputation: 1390

Capture short host name using built-in Perl modules?

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?

Upvotes: 9

Views: 10599

Answers (2)

Olaf Dietsche
Olaf Dietsche

Reputation: 74098

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`);

Upvotes: 12

xxfelixxx
xxfelixxx

Reputation: 6602

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.`);

Upvotes: 8

Related Questions