我正在扫描文件以查找某些值。对于每个值,我想创建一个输出文件并将匹配行转储到该特定输出文件中。这些值是预先未知的,所以当我遇到它们时,我需要使用它们。
为了避免一遍又一遍地打开和关闭文件,我试图测试文件句柄是否存在,如果存在,则写入它。如果没有,请打开它,写入内容,然后如果再次出现相同的值,则再次使用它。
我的脚本因以下错误而失败:
Scalar found where operator expected at get-authHost2.sh line 31, near ""$_ \n" $filehandle"
(Missing operator before $filehandle?)
Scalar found where operator expected at get-authHost2.sh line 35, near ""$_ \n" $filehandle"
(Missing operator before $filehandle?)
syntax error at get-authHost2.sh line 31, near ""$_ \n" $filehandle"
syntax error at get-authHost2.sh line 35, near ""$_ \n" $filehandle"
这是我到目前为止所拥有的...
use strict; use warnings;
my $outfile; my $filehandle; my $authHost;
my $filename = $1; open(my $fh, '<', $filename) or die "Could not open file '$filename' $!";
while (my $line = <$fh>) { chomp $line;
if (my ($authHost) = $line = /authHost="(.*?)"/ )
{
print "$authHost" ;
$outfile = print "$authHost-auth-events.out" ;
$filehandle = $authHost;
# if filehandle already exists, don't open the file again
if (-f $filehandle) {
print "$line \n" $filehandle;
}
else {
open(my $filehandle, '>>', $outfile) or die "Could not open file '$filename' $!";
print "$line \n" $filehandle;
}
} } close $fh;
我似乎找不到这个问题的答案。我发现的所有问题都是关于测试文件是否存在......而不是文件句柄本身是否存在。
如有任何帮助,我们将不胜感激。我不是程序员,所以要温柔! :-)
我的脚本因这些错误而失败
你的论据是倒退的。
print "$line \n" $filehandle;
应该是
print $filehandle "$line \n";
如果再次出现相同的值,则稍后再使用它。
我会使用哈希来存储打开的文件句柄(按文件名键入)。
请记住,进程可以拥有的打开文件句柄的数量是有限的。