如何让 Perl 匹配包含 windows EOL 字符的文件中的 \r
How to get Perl to match \r in files with windows EOL characters
我正在尝试编写一个 perl 脚本来识别具有 Windows 个 EOL 字符的文件,但是 \r
匹配似乎不起作用。
这是我的测试脚本:
#!/usr/bin/perl
use File::Slurp;
$winfile = read_file('windows-newlines.txt');
if($winfile =~ m/\r/) {
print "winfile has windows newlines!\n"; # I expect to get here
}
else {
print "winfile has unix newlines!\n"; # But I actually get here
}
$unixfile = read_file('unix-newlines.txt');
if($unixfile =~ m/\r/) {
print "unixfile has windows newlines!\n";
}
else {
print "unixfile has unix newlines!\n";
}
这是它的输出:
winfile has unix newlines!
unixfile has unix newlines!
我在 Windows 上 运行,我可以在 Notepad++ 中确认这些文件确实具有正确的 EOL 字符:
除非 binmode
为真(这不在您的代码中),否则 read_file
将在 Windows 上将 \r\n
更改为 \n
。来自 the code:
# line endings if we're on Windows
${$buf_ref} =~ s/52/2/g if ${$buf_ref} && $is_win32 && !$opts->{binmode};
为了保持原来的编码设置binmode,如图in the documentation:
my $bin = read_file('/path/file', { binmode => ':raw' });
我正在尝试编写一个 perl 脚本来识别具有 Windows 个 EOL 字符的文件,但是 \r
匹配似乎不起作用。
这是我的测试脚本:
#!/usr/bin/perl
use File::Slurp;
$winfile = read_file('windows-newlines.txt');
if($winfile =~ m/\r/) {
print "winfile has windows newlines!\n"; # I expect to get here
}
else {
print "winfile has unix newlines!\n"; # But I actually get here
}
$unixfile = read_file('unix-newlines.txt');
if($unixfile =~ m/\r/) {
print "unixfile has windows newlines!\n";
}
else {
print "unixfile has unix newlines!\n";
}
这是它的输出:
winfile has unix newlines!
unixfile has unix newlines!
我在 Windows 上 运行,我可以在 Notepad++ 中确认这些文件确实具有正确的 EOL 字符:
除非 binmode
为真(这不在您的代码中),否则 read_file
将在 Windows 上将 \r\n
更改为 \n
。来自 the code:
# line endings if we're on Windows
${$buf_ref} =~ s/52/2/g if ${$buf_ref} && $is_win32 && !$opts->{binmode};
为了保持原来的编码设置binmode,如图in the documentation:
my $bin = read_file('/path/file', { binmode => ':raw' });