Using Perl, how can I replace newlines with commas?

perl, regex

Solution

use strict;
use warnings;

my $infile = $ARGV[0] or die "$0 Usage:\n\t$0 <input file>\n\n";
open(my $in_fh , '<' , $infile) or die "$0 Error: Couldn't open $infile for reading: $!\n";
my $file_contents;
{

    local $/; # slurp in the entire file. Limit change to $/ to enclosing block.
    $file_contents = <$in_fh>

}
close($in_fh) or die "$0 Error: Couldn't close $infile after reading: $!\n";

# change DOS line endings to commas
$file_contents =~ s/\r\n/,/g;
$file_contents =~ s/,$//; # get rid of last comma

# finally output the resulting string to STDOUT
print $file_contents . "\n";

Your question text and example output were not consistent. If you're converting all line endings to commas, you will end up with an extra comma at the end, from the last line ending. But you example shows only commas between the numbers. I assumed you wanted the code output to match your example and that the question text was incorrect, however if you want the last comma just remove the line with the comment "get rid of last comma".

If any command is not clear, http://perldoc.perl.org/ is your friend (there is a search box at the top right corner).

Problem

I gave up on sed and I've heard it is better in Perl. I would like a script that can be called from the 'unix' command line and converts DOS line endings `CRLF` from the input file and replaces them with commas in the output file: like ``` myconvert infile > outfile ``` where infile was: ``` 1 2 3 ``` and would result in outfile: ``` 1,2,3 ``` I would prefer more explicit code with some minimal comments over "the shortest possible solution", so I can learn from it, I have no perl experience.

Original source