^M still at the end of my string even after chop/chomp

158 Views Asked by At

I am wanting to pass a string variable in a ssh command. You can see in the code below I ssh to a server then cd to a directory that I pass a variable to. (cd $orig) The variable is pulled from a file that I read in and put into an array. I think that is where my error is because there might be unwanted hidden characters after I used the split command to read in from the file.

Here is the error I get:

^M: not found Can't open perl script "AddAlias.pl": No such file or directory

SSHing to

It can't find my script because the CD to the folder fails.
Sometimes the error says that 'end of file' can't be found. Like I'm doing a CD command with a EOF hidden symbol.

And here is the code:

for(my $j=0; $j < $#servName+1; $j++)
{
   print "\nSSHing to $servName[$j]\n\n";
   my $orig = $scriptfileLoc[$j];
   #my $chopped = chop($orig);
   chop($orig);
   chomp($orig);
                
   print ("\n$orig\n");

   $sshstart = `ssh $servName[$j] "cd $orig; pwd; perl AddAlias.pl $aliasName $aliasCommand $addperl            $servProfileLoc[$j]"`;

   print $sshstart;
}  

It outputs the $orig variable and it looks fine after the chop and chomp. (Which I've done both by themselves and still got the same error) So I pass it in my SSH command and it doesnt work.

This script asks the user to choose to send a file to ALL servers or just one.

2

There are 2 best solutions below

0
Narek On

"^M" is carriage return a.k.a "\r". Use regex to remove it:

$orig =~ s/\r//g;
0
knittl On

To remove CR (^M) from the end of lines, use the following regex:

$orig =~ s/\r$//gm;

Anchoring at the line end guarantees that any other carriage return characters are not removed from your input. (You probably don't them there either, but to normalize line endings, it's better to not touch other characters).

g enables global matches (not only the first) and m enables multiline mode, so that $ matches the end of each line in a multiline string, not only the end of the string.