如何使用 Perl 提取和保存文本?
没有提取数据输出到data2.txt? 代码出了什么问题?
MyFile.txt
ex1,fx2,xx1
mm1,nn2,gg3
EX1,hh2,ff7
这是我在 data2.txt 中想要的输出:
ex1,fx2,xx1
EX1,hh2,ff7
#! /DATA/PLUG/pvelasco/Softwares/PERLINUX/bin/perl -w
my $infile ='My1.txt';
my $outfile ='data2.txt';
open IN, '<', $infile or die "Cant open $infile:$!";
open OUT, '>', $outfile or die "Cant open $outfile:$!";
while (<IN>) {
if (m/EX$HF|ex$HF/) {
print OUT $_, "\n";
print $_;
}
}
close IN;
close OUT;
No extracted data output to data2.txt? What goes wrong to the code?
MyFile.txt
ex1,fx2,xx1
mm1,nn2,gg3
EX1,hh2,ff7
This is my desired output in data2.txt:
ex1,fx2,xx1
EX1,hh2,ff7
#! /DATA/PLUG/pvelasco/Softwares/PERLINUX/bin/perl -w
my $infile ='My1.txt';
my $outfile ='data2.txt';
open IN, '<', $infile or die "Cant open $infile:$!";
open OUT, '>', $outfile or die "Cant open $outfile:$!";
while (<IN>) {
if (m/EX$HF|ex$HF/) {
print OUT $_, "\n";
print $_;
}
}
close IN;
close OUT;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这个正则表达式没有意义:
$HF 应该是一个变量吗? 你想匹配什么?
另外,您编写的每个 Perl 脚本中的第二行应该是:
它会让 Perl 捕获此类错误并告诉您它们,而不是默默地忽略它们。
This regex makes no sense:
Is $HF supposed to be a variable? What are you trying to match?
Also, the second line in every Perl script you write should be:
It will make Perl catch such mistakes and tell you about them, rather than silently ignoring them.
抱歉,如果这看起来像是在说明明显的出血,但是有什么问题
......或者如果您真的想在 perl 中执行此操作(并且这没有任何问题):
这假设请求的目的是查找以EX,不区分大小写。
Sorry if this seems like stating the bleeding obvious, but what's wrong with
... or if you really want to do it in perl (and there's nothing wrong with that):
This assumes the purpose of the request is to find lines that start with EX, with case-insensitivity.
当我运行您的代码,但将输入文件命名为
My1.txt
而不是MyFile.txt
时,我得到了所需的输出 - 空行除外,您可以通过删除来删除空行print 语句中的, "\n"
。When I run your code, but name the input file
My1.txt
instead ofMyFile.txt
I get the desired output - except with empty lines, which you can remove by removing the, "\n"
from the print statement.文件名不匹配。
是的,总是总是使用严格;
你也可以chomp $line并且(如果使用perl 5.10)说$line em> 而不是打印“$line\n”。
The filenames don't match.
And yes, always always use strict;
You could also chomp $line and (if using perl 5.10) say $line instead of print "$line\n".