2

好吧,所以我又回来了另一个问题。我知道在 Python 中有一种读取文件的方法,而无需指定它将是哪个文件,直到您进入命令提示符。所以基本上你可以设置脚本,这样你就可以读取任何你想要的文件,而不必每次都返回并更改编码。有没有办法在 Perl 中做到这一点?如果是这样,你也可以写这样的文件吗?谢谢。

这就是我所拥有的:

open (LOGFILE, "UNSUCCESSFULOUTPUT.txt") or die "Can't find file";       
open FILE, ">", "output.txt" or die $!;

while(<LOGFILE>){
print FILE "ERROR in line $.\n" if (/Error/);
}






close FILE;
close LOGFILE;                  

这就是我的名字:

#!/usr/local/bin/perl


my $argument1 = $ARGV[0];
open (LOGFILE, "<$argument1") or die "Can't find file";     

open FILE, ">>output.txt" or die $!;


while(<LOGFILE>){
print FILE "ERROR in line $.\n" if (/Error/);
}





close FILE;
close LOGFILE;

它仍然没有附加......

4

3 回答 3

3

命令行参数在@ARGV. 您可以随心所欲地使用它们,包括将它们作为文件名传递给open.

my ($in_qfn, $out_qfn) = @ARGV;
open(my $in_fh,  '<', $in_qfn ) or die $!;
open(my $out_fh, '>', $out_qfn) or die $!;
print $out_fh $_ while <$in_fh>;

但这不是一种非常统一的做事方式。在 unix 传统中,将从命令行上指定的每个文件读取以下内容,一次一行:

while (<>) {
    ...
}

输出通常通过重定向放置在文件中。

#!/usr/bin/env perl
# This is mycat.pl
print while <>;

# Example usage.
mycat.pl foo bar > baz

# Edit foo in-place.
perl -i mycat.pl foo

通常唯一接触@ARGV的是处理选项,即便如此,人们通常使用Getopt::Long而不是直接接触@ARGV


关于您的代码,您的脚本应该是:

#!/usr/bin/env perl
while (<>) {
   print "ERROR in line $.\n" if /Error/;
}

用法:

perl script.pl UNSUCCESSFULOUTPUT.txt >output.txt

如果您制作可执行文件() ,则可以摆脱perl该命令。script.plchmod u+x script.pl

于 2012-06-06T17:05:43.210 回答
2

我假设您在问如何将参数传递给 perl 脚本。这是通过@ARGV变量完成的。

use strict;
use warnings;

my $file = shift;   # implicitly shifts from @ARGV
print "The file is: $file\n";

您还可以利用菱形运算符的魔力<>,它将脚本的参数作为文件打开,或者如果没有提供参数,则使用 STDIN。菱形运算符用作普通文件句柄,通常while (<>) ...

预计到达时间:

使用您提供的代码,您可以通过执行以下操作使其更加灵活:

use strict;
use warnings;  # always use these
my $file    = shift;                 # first argument, required
my $outfile = shift // "output.txt"; # second argument, optional

open my $log, "<", $file    or die $!;
open my $out, ">", $outfile or die $!;

while (<$log>) {
    print $out "ERROR in line $.\n" if (/Error/);
}

另请参阅 ikegami 的回答,了解如何使其更像其他 unix 工具,例如接受 STDIN 或文件参数,并打印到 STDOUT。

正如我在您之前的问题中所评论的那样,您可能只是希望使用已经存在的工具来完成这项工作:

grep -n Error input.txt > output.txt
于 2012-06-06T17:06:25.870 回答
2

这就是我相信你想要的:

#!usr/bin/perl
my $argument1 = $ARGV[0];

open (LOGFILE, "<$argument1") or die "Can't find file";       
open (FILE, ">output.txt") or die $!;

while(<LOGFILE>){
print FILE "ERROR in line $.\n" if (/Error/);
}

close FILE;
close LOGFILE; 

从命令行运行:

> perl nameofpl.pl mytxt.txt

对于附加更改此行:

 open (FILE, ">output.txt") or die $!;

与非常相似的:

 open (FILE, ">>output.txt") or die $!;
于 2012-06-06T17:31:12.313 回答