Since this is a different topic than the one in the root node, if you have more issues/questions, I recommend starting a new thread. There are a few issues with the code, and potential improvements:
- Use strict and warnings! For example it would have given you a hint that you have a typo in the line print File "$files[$x] is incorrect<br>"; - in fact this is probably one of the issues that is making you think the regex isn't working, when it actually is.
- You need to check the return value of open for errors, and I'd strongly recommend to use lexical filehandles and the 3-argument form, as in open my $fh, '<:raw', $files[$x] or die "$files[$x]: $!";
- You should open your files with the :raw layer as I showed above, or binmode them after opening (as the AM post points out), because otherwise, under Windows, your files will be opened with the :crlf layer by default (see PerlIO), another reason your test code might not be working.
- You've also got a typo in the two open (FILE, "<$files[$x]); lines (again, Use strict and warnings).
- When reading the entire file into memory, you don't need to read it in a loop, there is a trick to slurp the entire file into memory at once: my $tmp = do { local $/; <$fh> };
Personally I find the regex s/[\n\r][\n\r]/\n/g a little too flexible: If the file for some reason contains mixed CR/LF line endings, this regex might muck them up even more. Plus, if there are mixed endings, just checking the first line isn't enough. Here's how I might have written a script like this, even though there is no need to reinvent this wheel - for example, the fromdos tool from the Tofrodos package could already be installed on your system.
#!/usr/bin/env perl
use warnings;
use strict;
use Getopt::Std 'getopts';
our $VERSION = '0.01';
$Getopt::Std::STANDARD_HELP_VERSION = 1;
getopts('qi', \my %opts)
or die "Usage: $0 [-q] [-i] FILE(s)\n";
if ( !@ARGV || (!$opts{i} && $opts{q}) )
{ warn "No actions to perform\n"; exit 1 }
for my $file (@ARGV) {
open my $ifh, '<:raw', $file or die "$file: $!";
my $data = do { local $/; <$ifh> };
close $ifh;
if (not $opts{q}) {
my $cr = () = $data=~/\x0D(?!\x0A)/g;
my $lf = () = $data=~/(?<!\x0D)\x0A/g;
my $crlf = () = $data=~/\x0D\x0A/g;
print "$file: ", ( join(', ', $cr?"$cr CR":(), $lf?"$lf LF":()
+,
$crlf?"$crlf CRLF":() ) || 'no CR or LF' ), "\n";
}
if ($opts{i}) {
$data =~ s/\x0D\x0A?|\x0A/\n/g;
open my $ofh, '>:raw', $file or die "$file: $!";
print $ofh $data;
close $ofh;
}
}