简体   繁体   English

Perl - 使用打印功能时出现意外结果

[英]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

===========================================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)此外,我正在尝试将文件名创建为主机名,正如您在上面的代码中看到的那样,它将文件名创建为主机名,但是我看到一个换行符附加到文件名中,这是我在列出目录中的文件时注意到的(使用 ls - ltr)(即,文件名本身显示为两行 - 第一行是主机名,并在文件名后附加一个空的换行符)

You need to remove the getting hostname entermark with chomp() function.您需要使用chomp()函数删除获取hostname entermark

$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)

The line线

$outfile = `hostname`;

will run the hostname command and return all the data written to STDOUT, including the terminating EOL.将运行hostname命令并返回写入 STDOUT 的所有数据,包括终止 EOL。 This means you end up with a filename that include the terminating EOL character.这意味着您最终会得到一个包含终止 EOL 字符的文件名。 What the filesystem does with that is OS dependent, but on Linux you will end up with a file that include the EOl character.文件系统的作用取决于操作系统,但在 Linux 上,您最终会得到一个包含 EOl 字符的文件。

You can remove that with the chomp你可以用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
===========================================

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM