Home > Software design >  How to remove carriage return in Perl properly?
How to remove carriage return in Perl properly?

Time:02-02

I have a code that looks like this


sub ConvertDosToUnix{
    my $file = shift;
    open my $dosFile, '>', $file or die "\nERROR: Cannot open $file";
    select $dosFile;
    print("Converting Dos To Unix");
    `perl -p -i -e "s/\r//g" $dosFile`;
    close $dosFile;
}

Also, the perl command works when I used that outside the subroutine or in the main function. But when I created a separate subroutine for converting dos to unix, I got an error that says:

sh: -c: line 0: syntax error near unexpected token `('*

//g" GLOB(0x148b990)' -p -i -e "s/

In which I don't understand.

Also, I also tried dos2unix but for some reason, it doesn't totally remove all the carriage returns like the perl command.

Thanks!!!

CodePudding user response:

Honestly, you seem a little confused.

The code you have inside backticks is a command that is run by the shell. It needs to be passed a filename. You have your filename in the variable $file, but you pass it the variable $dosFile which contains a file handle (which stringifies to "GLOB(0x148b990)" - hence your error message).

So all your work opening the file is wasted. Really, all you wanted was:

`perl -p -i -e "s/\r//g" $file`

But your system almost certainly has dos2unix installed.

`dos2unix $file`

I should also point out that using backticks is only necessary if you want to capture the output from the command. If, as in this case, you don't need the output, then you should use system() instead.

system('dos2unix', $file);
  • Related