Search code examples
perlcsvline-breaks

Understand Error in Perl script


I'm trying to write a Perl script that convert the line endings of some CSV files stored in a folder. I am a Perl newbie so any help would be appreciated.

use strict;
use warnings;

my @files = glob "*.csv";

foreach my $i (@files) {

    system('perl -i.bak -pe "s/\R/\n/g" '.$i.'') or die "$?";

}

After converting the first file the script terminate with this error:

0 at script_conversione_linebreaks.pl at line 8.

Is it the right way to do the conversion? Or I have to pass all CSV files at once in the system statement?


Solution

  • About your error message, since the return value of system is the status of the program, if the program was successful you would get 0. This means you will die, since 0 is interpreted as false.

    use strict;
    use warnings;
    
    my @files = glob "*.csv";
    
    foreach my $i (@files) {
        system('perl -i.bak -pe "s/\R/\n/g" ' . $i) and die "$?"; # Note the `and`
    }
    

    As a further notice: you are running a subprocess for every csv file. This is bad in terms of performances. You may want to consider running a single command from your shell:

    perl -i.bak -pe 's/\R/\n/g' *.csv
    

    I believe however this is the kind of situation in which you should choose another weapon.

    Does this help?

    #!/bin/sh
    for i in *.csv; do cp $i $i.bak; dos2unix $i; done
    

    Edit: as pointed out by @AkHolland in the comment, you could directly call dos2unix on all the files at once, and let it cycle on them. This will not generate backups, but it's also true that dos2unix will hardly go wrong on text files.