best worker
best worker

Reputation: 55

Perl - getting unexpected result while using print function

Hi I am trying to create a file with contents as given below

$outfile = `hostname`;
$txt = "\nHealth check results - ";
$txt .= `hostname`;
$txt .= "\n===========================================";
print "$txt";

# Create output file to store the HC results.

open $fh, '>', $outfile or die "Can't open $outfile \n";
print $fh $txt;
close ($fh)

the output comes like below

Health check results - XXHOSTNAMEXX

===========================================XXHOSTNAMEXX

why is the hostname getting printed twice, which I dont need the second time printing of hostname at the end.

Also I am trying to create filename as hostname as you see above in code, where it creates the file name as hostname, however I see a newline character is appended to the filename which I noticed while listing the files in the dir(using ls -ltr)(ie., the filename itlself is displayed with two lines - first line is hostname and an empty newline appended to the filename)

Upvotes: 0

Views: 75

Answers (2)

ssr1012
ssr1012

Reputation: 2589

You need to remove the getting hostname entermark with chomp() function.

$outfile = `hostname`;

chomp $outfile;  #----> Need to chomp (Remove last entermark)

$txt = "\nHealth check results - ";

$txt .= $outfile; #----> Already you got the hostname hence just store $outfile 

$txt .= "\n===========================================";
print "$txt";

# Create output file to store the HC results.

open $fh, '>', $outfile or die "Can't write $outfile \n";
print $fh $txt;
close ($fh)

Upvotes: 1

pmqs
pmqs

Reputation: 3705

The line

$outfile = `hostname`;

will run the hostname command and return all the data written to STDOUT, including the terminating EOL. This means you end up with a filename that include the terminating EOL character. What the filesystem does with that is OS dependent, but on Linux you will end up with a file that include the EOl character.

You can remove that with the chomp

$outfile = `hostname`;
chomp $outfile;

updated script looks like this

$outfile = `hostname`;
chomp $outfile;

$txt = "\nHealth check results - ";
$txt .= $outfile;
$txt .= "\n===========================================\n";
print "$txt";

# Create output file to store the HC results.

open $fh, '>', $outfile or die "Can't open $outfile \n";
print $fh $txt;
close ($fh) ;

I get this when I run it

Health check results - XXHOSTNAMEXX
===========================================

Upvotes: 1

Related Questions