我的测试文件有“n”行,每行之间有一个 ^M,这反过来又使它成为一个大字符串。我正在使用的代码打开所述文件,应该解析出一个标题,然后是后续行,然后搜索目录路径和文件名。但是因为文件只是作为一个大字符串结束它不能正常工作
#!/usr/bin/perl
#use strict;
#use warnings;
open (DATA, "<file.txt") or die ("Unable to open file");
my $search_string = "Directory Path";
my $column_search = "Filename";
my $header = <DATA>;
my @header_titles = split /\t/, $header;
my $extract_col = 0;
my $col_search = 0;
for my $header_line (@header_titles) {
last if $header_line =~ m/$search_string/;
$extract_col++;
}
for my $header_line (@header_titles) {
last if $header_line =~m/$column_search/;
$col_search++;
}
print "Extracting column $extract_col $search_string\n";
while ( my $row = <DATA> ) {
last unless $row =~ /\S/;
chomp $row;
my @cells = split /\t/, $row;
$cells[74]=~s/:/\//g;
$cells[$extract_col]= $cells[74] . $cells[$col_search];
print "$cells[$extract_col] \n";
}
当我在 VI 中打开测试文件时,我使用了
:%s/^M/\r/g
这删除了 ^M 但我如何在这个 perl 程序中做到这一点?当我尝试一个测试程序并插入该程序时
s\^M/\r/g
并将其写入不同的文件,结果显示为很多汉字。
最佳答案
在开始读取文件之前,设置 $/
至 "\r"
.这默认设置为换行符,这对于 UNIX 风格的行尾来说很好,对于 DOS 风格的行尾几乎没问题,但对于你看到的旧 Mac 风格的行尾来说没用。如果你安装了 mac2unix,你也可以在你的输入文件上尝试它。
有关更多信息,请在 the perlvar manpage 中查找“INPUT_RECORD_SEPARATOR” .
关于perl - 如何用perl中的新行替换^M,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7175977/