String 如何在行中添加特定字符串
我有以下遗留代码:String 如何在行中添加特定字符串,string,perl,String,Perl,我有以下遗留代码: open(FILE_Errors,">Errors.txt") || die "Error at >"; undef(@arrayrow); open(File_To_Read,"<$file") || die "File not Found"; while($row=<File_To_Read>) { push(@arrayrow,$row); } close(Fi
open(FILE_Errors,">Errors.txt") || die "Error at >";
undef(@arrayrow);
open(File_To_Read,"<$file") || die "File not Found";
while($row=<File_To_Read>) {
push(@arrayrow,$row);
}
close(File_To_Read);
foreach(@arrayrow) {
if($_=~ m/errorcode: 230/i) {
print FILE_Errors "$_";
} elsif($_=~ m/errors/i) {
print FILE_Errors "$_";
}
}
}
close (file);
文件B.txt:
lorem ipsum
loem errors ipsum
Errors.txt:
lorem ipsum错误代码:230
同侧韧带
现在,它应该附加行来自哪个文件。
Errors.txt:
lorem ipsum errorcode: 230 A.txt
loem errors ipsum B.txt
我尝试的内容和相关输出(对我来说没有意义):
其中行等于lorem ipsum errorcode.
print FILE_Errors "$file $_" # produces:
A.txt line
A.txt line
A.txt line
B.txt line
B.txt line
及
如何安排变量以获得:
line A.txt
line B.txt
附言:我已经读过了
编辑1:@Jonathan Leffler
chomp;
print FILE_Errors "$_ $file\n";
#will produce:
A.txt line
A.txt line
A.txt line
B.txt line
B.txt line
通过将语句更改为“$file$\n”,它将起作用。谢谢大家! 使用
chomp
删除尾随的换行符,然后在打印中添加文件名和换行符:
chomp;
print FILE_Errors "$_ $file\n";
请注意,在脚本中,
close(文件)
不会关闭打开的任何一个文件(但在脚本提取中该行和大括号之前的那一行和大括号是插入者;问题没有显示打开的大括号)。此外,除非阵列上的处理比显示的要多,否则不需要将整个文件读入内存;您可以一次处理一行。如果一次需要内存中的所有数据,可以将整个while
循环减少为:
@arrayrow = <File_to_Read>;
@arrayrow=;
您的脚本在很大程度上可以被Perl内置功能所取代,只需执行以下操作:
perl -nlwe'/error(?:s|code: 230)/i and print' input1 input2 ... > errors.txt
您还可以将其放置在源文件中:
use strict;
use warnings;
while (<>) {
/error(?:s|code: 230)/i and print;
}
虽然就我个人而言,我更喜欢键入我自己的路径,因为这不太可能让你感到惊讶
请注意,正则表达式是两个正则表达式的组合版本。另外,请注意,您应该使用三个参数
open
和显式模式“>”
、词法文件句柄(而不是全局)以及显式错误检查,使用$代码>错误以显示错误。谢谢!-这个@arrayrow=;给我留下了深刻的印象;可能性@如果你喜欢,你应该知道,所有的Perl代码都有这样的可能性,如果你记住考虑列表上下文与标量上下文。file handle readline()函数在标量上下文(例如,my$line=
)中是一个迭代器,但在列表上下文中它会一次耗尽,例如在使用数组时。
perl -nlwe'/error(?:s|code: 230)/i and print' input1 input2 ... > errors.txt
use strict;
use warnings;
while (<>) {
/error(?:s|code: 230)/i and print;
}
my $error_output = shift || "errors.txt";
open my $outfh, ">", $error_output or die "Cannot open $error_output: $!";