【问题标题】:Writing results in a text file with perl使用 perl 将结果写入文本文件
【发布时间】:2013-09-26 21:54:24
【问题描述】:

脚本在结果文本文件中打印整行文本文件时遇到问题:

use strict;
use warnings;
use autodie;
my $out = "result2.txt";
open my $outFile, ">$out" or die $!;
my %permitted = do {
open my $fh, '<', 'f1.txt';
map { /(.+?)\s+\(/, 1 } <$fh>;
};

open my $fh, '<', 'f2.txt';
while (<$fh>) {
my ($phrase) = /(.+?)\s+->/;

if ($permitted{$phrase}) { 
print $outFile $fh;
 }
close $outFile;

问题出在这一行

print $outFile $fh;

有什么想法吗?

谢谢

【问题讨论】:

  • 您正在尝试将文件句柄 $fh 打印到 $outFile。将该行更改为print $outFile $_;
  • 使用 autodie 模块,您不需要 or die $!; 这就是 autodie 存在的原因。

标签: perl


【解决方案1】:

print $outFile $fh 正在将文件句柄 $fh 的值打印到文件句柄$outFile。相反,您想打印整个当前行,即$_

还有其他一些可以改进的地方

  • 您应该始终使用open三参数形式,因此打开模式作为第二个参数单独出现

  • 无需测试open 的成功与否

  • 如果你有一个包含输出文件名的变量,那么你真的应该有两个输入文件名的变量

这就是您的程序的外观。希望对你有帮助。

use strict;
use warnings;
use autodie;

my ($in1, $in2, $out) = qw/ f1.txt f2.txt result2.txt /;

my %permitted = do {
  open my $fh, '<', $in1;
  map { /(.+?)\s+\(/, 1 } <$fh>;
};

open my $fh,    '<', $in2;
open my $outfh, '>', $out;

while (<$fh>) {
  my ($phrase) = /(.+?)\s+->/;
  if ($permitted{$phrase}) {
    print $outfh $_;
  }
}

close $outfh;

【讨论】:

    【解决方案2】:

    我想你想在这里print $outfile $phrase,不是吗?您当前的行正在尝试将文件句柄引用 ($fh) 打印到文件 ($outfile)。

    此外,作为 perl 最佳实践的一部分,您需要将三个参数 open 用于您的第一个开放行:

     open my $outFile, ">", $out or die $!;
    

    (FWIW,您已经在使用 3-arg open 来进行另外两个对 open 的调用。)

    【讨论】:

    • 谢谢,不,如果条件为真,我想打印整行“f2.txt”
    【解决方案3】:

    虽然Borodin 为您的问题提供了一个很好的解决方案,但这里有另一个选项,您可以在命令行上将“in”文件的名称传递给脚本,并让 Perl 处理这些文件的打开和关闭:

    use strict;
    use warnings;
    
    my $file2 = pop;
    my %permitted = map { /(.+?)\s+\(/, 1 } <>;
    
    push @ARGV, $file2;
    
    while (<>) {
        my ($phrase) = /(.+?)\s+->/;
        print if $permitted{$phrase};
    }
    

    用法:perl script.pl inFile1 inFile2 [&gt;outFile]

    最后一个可选参数将输出定向到文件。

    pop 命令从@ARGV 中隐式删除inFile2 的名称,并将其存储在$file2 中。然后,使用 &lt;&gt; 指令读取 inFile1。然后 inFile2 的文件名将 pushed 到 @ARGV 上,如果 $permitted{$phrase} 为真,则读取该文件并打印一行。

    在没有最后一个可选参数的情况下运行脚本会将结果(如果有)打印到屏幕上。使用最后一个参数将输出保存到文件中。

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-14
      • 1970-01-01
      • 2011-09-30
      • 2023-03-12
      • 1970-01-01
      相关资源
      最近更新 更多