[英]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"
. 当我将文本追加到文件时,我想为文件添加正确的结尾:对于Unix: "\\n"
和对于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
: 使用:crlf
句柄,例如使用use open
和use if
:
use if ($^O eq "MSWin32") => open qw(IO :crlf :all);
The relevant documentations: 相关文件:
If the platform is MS-DOS like and normally does CRLF to "\\n" translation for text files then the default layers are : 如果平台类似于MS-DOS,并且通常对文本文件进行CRLF到“ \\ n”的转换,则默认层为:
unix crlf
So the above code should be redundant, but that's what you're asking for. 因此,上面的代码应该是多余的,但这就是您要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.