简体   繁体   中英

Add default system newline in Perl

When I append text to a file I would like to add the correct line ending for the file: for Unix: "\\n" and for Windows "\\r\\n" . However, I could not find an easy way to do this. This was the best I could come up with:

use strict;
use warnings;
use Devel::CheckOS ();

my $fn = 'file';
open (my $fh, '<', $fn) or die "Could not open file '$fn': $!\n";
my $first_line = <$fh>;
my $len = length $first_line;
my $file_type = "undetermined";
if ($len == 1) {
    $file_type = "Unix" if $first_line eq "\n";
}
if ($len >= 2) {
    if (substr($first_line, $len - 1, 1) eq "\n") {
        if (substr($first_line, $len - 2, 1) eq "\r") {
            $file_type = "DOS";
        } else {
            $file_type = "Unix";
        }
    }
}
close $fh;
if ($file_type eq "undetermined") {
    $file_type = get_system_file_type();
}
print "File type: $file_type.\n";

sub get_system_file_type {
    return Devel::CheckOS::os_is('MicrosoftWindows') ? "DOS" : "Unix"; 
}

Is it really necessary to do all these checks? Or are there simpler ways to do this?

Use the :crlf handle, for example with use open and use if :

use if ($^O eq "MSWin32") => open qw(IO :crlf :all);

The relevant documentations:

  • PerlIO for the io layers. Note that this page states:

If the platform is MS-DOS like and normally does CRLF to "\\n" translation for text files then the default layers are :

unix crlf

So the above code should be redundant, but that's what you're asking for.

  • perlvar for the $^O variable.

  • open for the open pragma.

  • if for conditional loading of modules.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM