重定向文件文本中的结果

时间:2014-01-21 21:39:31

标签: perl file redirect

我做一个perl脚本,它直接从第一个文件的内容创建一个哈希,然后读取第二个文件的每一行,检查哈希值以查看是否应该打印它。

这是perl脚本:

use strict;
use warnings;
use autodie;

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

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

我正在寻找如何在文件文本中打印结果,因为此脚本实际上会在屏幕上打印结果。

提前谢谢。

亲切

3 个答案:

答案 0 :(得分:2)

$ perl thescript.pl > result.txt

将运行您的脚本并将打印输出放在result.txt

或者,从脚本本身:

use strict;
use warnings;
use autodie;

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

# Open result.txt for writing:
open my $out_fh, '>', 'result.txt' or die "open: $!";

open my $fh, '<', 'f2.txt';
while (<$fh>) {
    my ($phrase) = /(.+?)\s+->/;
    # print output to result.txt
    print $out_fh $_ if $permitted{$phrase};
}

答案 1 :(得分:2)

在写入模式下打开一个新的文件句柄,然后打印到它。有关详细信息,请参阅perldoc -f print或http://perldoc.perl.org/functions/print.html

...
open my $fh, '<', 'f2.txt';
open my $out_fh, '>', 'output.txt';
while (<$fh>) {
  my ($phrase) = /(.+?)\s+->/;
  print $out_fh $_
      if $permitted{$phrase};
}

答案 2 :(得分:2)

map ping文件内容首先生成所有文件行的列表。除非文件非常大,否则这不一定是坏事。 grebneke展示了如何使用> result.txt将输出定向到文件。鉴于此问题以及(可能的)map问题,请考虑将这两个文件从命令行传递到脚本,并使用while s处理它们:

use strict;
use warnings;

my %permitted;

while (<>) {
    $permitted{$1} = 1 if /(.+?)\s+\(/;
    last if eof;
}

while (<>) {
    print if /(.+?)\s+->/ and $permitted{$1};
}

用法:perl script.pl f1.txt f2.txt > result.txt

希望这有帮助!