Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Get hostname and use within system command

Status
Not open for further replies.

TSch

Technical User
Jul 12, 2001
557
DE
Hi folks,

somehow it seems I'm too stupid for this task that however should be quite easy.

What I'm trying to do is define a variable containing the hostname of the current machine (I'm using Linux). Then I'd like to call a system command containing this variable.

Here's an example ...
(Note: This is NOT the whole script ...)

If I try the following, everything is fine:

Code:
use strict;
my $hn = system("hostname");
print $hn;

However, if I change it like this:

Code:
... Generating some output ...
use strict;
my $hn = system("hostname");
system ("echo \"$_\" | mail -s \"$hn is reporting an Error.\" recipient");

The mail I receive's got the following header:

Code:
0 is reporting an Error.

Instead of containing the hostname as it should.

So I tried the following approach:

Code:
use strict;
my @hn = system("hostname");
print @hn;

The Output was quite confusing as it seems that the hostname command returns 2 values:

Code:
serverA
0

"So what" I thought and assuming there are 2 values being returned by the hostname command I simply used an array and tried to force him to return only the first value ... Like this:

Code:
... Generating some output ...
use strict;
my @hn = system("hostname"];
system ("echo \"$_\" | mail -s \"$hn[0] is reporting an Error.\" recipient");

But still I keep getting this stupid 0 returned ...

Where's the mistake here ?

Regards
Thomas
 
Hi

Thomas said:
Where's the mistake here ?
[ol]
[li]Not reading the [tt]system()[/tt] function's documentation. It returns the exit code of the executed command. Its documentation also mentions the alternatives to capture the executed command's output.[/li]
[li]Not using the dedicated Sys::Hostname core module.[/li]
[/ol]


Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top