Greetings,
Tiago, adding to Jim's and Andy's wisdom. Here is the complete code snippet
[code]
use strict;
use warnings;
unless(@ARGV == 1) {
die "Usage : $0 <filename>\n";
}
my $file = shift;
my $fin = IO::File->new($file, 'r') or die "Cannot open file for read ($!)";
$fin->binmode(":raw");
my $content = do { local $/; <$fin> };
my $cr = $content =~ tr/\r/\r/;
my $lf = $content =~ tr/\n/\n/;
my $crlf = $content =~ s/\r\n/\r\n/g;
$fin->close();
$cr -= $crlf;
$lf -= $crlf;
if(($cr == 0) && ($lf == 0) && ($crlf != 0)) {
print "DOS/Windows";
#Do Something
} elsif (($cr == 0) && ($lf != 0) && ($crlf == 0)) {
print "Unix/Linux";
#Do Something
} elsif (($cr != 0) && ($lf == 0) && ($crlf == 0)) {
print "Mac";
#Do Something
} else {
print "Binary file";
#Do Something
}
[/code]
[output]
>./demo.pl important01.txt
Mac
>./demo.pl important02.txt
Unix/Linux
>./demo.pl important03.txt
DOS/Windows
>./demo>demo.pl eagle.jpg
Binary file
[/output]
Note: The following file format is fed into the command line. The file
important01 is of type Mac Line Endings, important02.txt is of Unix Line
Endings, important03.txt is of Windows Line Endings and finally eagle.jpg is of
type Binary
best,
Shaji
-------------------------------------------------------------------------------
Your talent is God's gift to you. What you do with it is your gift back to God.
-------------------------------------------------------------------------------
----- Original Message -----
From: Jim Gibson <[email protected]>
To: Perl Beginners <[email protected]>
Cc:
Sent: Saturday, 23 February 2013 5:20 AM
Subject: Re: Line Endings
On Feb 22, 2013, at 10:40 AM, Andy Bach wrote:
> On Fri, Feb 22, 2013 at 12:08 PM, Tiago Hori <[email protected]> wrote:
>
>> What I was wondering is: is there any way to force perl to use other line
>> ending characters, like MacOS CR?
>>
Another approach is to read the entire file into a scalar and then split on the
regular expression [\r\n]+
Read the file into a scalar:
my $content = do { local $/; <$fh> };
or using the File::Slurp module:
my $content = read_file($filename);
Then split into lines:
my @lines = split(/[\r\n]+/,$content);
You do end up with two copies of the file contents, so this method is not
efficient in terms of memory usage.
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/