【问题标题】:How can I extract and save text using Perl?如何使用 Perl 提取和保存文本?
【发布时间】:2008-10-17 07:00:27
【问题描述】:

没有提取的数据输出到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;

【问题讨论】:

  • 使用三个参数打开。

标签: regex perl text extract


【解决方案1】:

这个正则表达式没有意义:

m/EX$HF|ex$HF/

$HF 应该是一个变量吗?你想匹配什么?

另外,您编写的每个 Perl 脚本的第二行应该是:

use strict;

它会让 Perl 捕捉到这些错误并告诉你它们,而不是默默地忽略它们。

【讨论】:

  • ... 第三个应该是use warnings
  • 那么他为什么不在第一行添加 -Mstrict 呢?
【解决方案2】:
while (<IN>) {
  if (m/^(EX|ex)\d.*/) {   
    print OUT "$_";      
    print $_;   
  }
}

【讨论】:

  • 另外,如果您不需要输入文件中所有行的(调试?)输出,您可以将其简化为单行 perl -ne 'print if /^(EX|例如)\d/'
  • perl 高尔夫有它的位置,但我宁愿人们将可读的代码投入生产。
  • 这个简单到可以使用单行。
【解决方案3】:

很抱歉,这似乎说明流血很明显,但有什么问题

grep -i ^ex < My1.txt > data2.txt

...或者如果您真的想在 perl 中执行此操作(这并没有错):

perl -ne '/^ex/i && print' < My1.txt > data2.txt

这假设请求的目的是查找以 EX 开头的行,不区分大小写。

【讨论】:

    【解决方案4】:

    当我运行您的代码,但将输入文件命名为 My1.txt 而不是 MyFile.txt 时,我得到了所需的输出 - 除了空行,您可以通过从 print 语句中删除 , "\n" 来删除它。

    【讨论】:

      【解决方案5】:

      文件名不匹配。

      open(my $inhandle, '<', $infile)   or die "Cant open $infile: $!";
      open(my $outhandle, '>', $outfile) or die "Cant open $outfile: $!";
      
      while(my $line = <$inhandle>) {   
      
          # Assumes that ex, Ex, eX, EX all are valid first characters
          if($line =~ m{^ex}i) {         # or   if(lc(substr $line, 0 => 2) eq 'ex') {
              print { $outhandle } $line;      
              print $line;
          }
      }
      

      是的,总是总是 使用严格的;

      你也可以 chomp $line 并且(如果使用 perl 5.10)说 $line 而不是 print "$line\n"

      【讨论】:

      • 这一行的大括号是干什么用的?打印 { $outhandle } $line;
      • 它有助于避免错误,例如... print $outhandle, $line; (逗号表示 print 不会将 $outhandle 识别为文件句柄)。它是 Damian Conway 的“Perl 最佳实践”的推荐。
      猜你喜欢
      • 2011-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-18
      • 2014-06-09
      • 1970-01-01
      • 2013-04-24
      • 1970-01-01
      相关资源
      最近更新 更多