I’ve got a problem in my Perl program when I try to combine a computer name in a string with a string with dot (.), please see the code below.
#!/usr/bin/perl
use strict;
use warnings;
chomp(my $COMPUTERNAME = `hostname`); #this should give the computername e.g CH-B7G33
my $complog = $COMPUTERNAME.".log";
print "$complog";
The expected output would be.
CH-B7G33.log
But what I got is wrong, it printed out.
.logB7G33
Did I do something wrong in the code? Please help me, I’m a Perl beginner and by the way sorry to my English.
The return value from your system call contains a
\rat the end, whichchompis not clearing away. So your string ends up looking likeCH-B7G33\r.logwhich when printed causes the terminal to displayCH-B7G33then move the cursor back to the start of the line, and then display.logwhich overwrites the characters, leading to the incorrect output you saw.Using a substitution works well, and will handle both
\rand\nline endings (and other trailing space, as written here).