perl 打开文件句柄如果它不存在,使用它如果它是

xxb16uws  于 7个月前  发布在  Perl
关注(0)|答案(1)|浏览(85)

我正在扫描一个文件,寻找特定的值。对于每个值,我想创建一个输出文件,并将匹配的行转储到该特定的输出文件中。这些值事先是未知的,所以当我遇到它们时,我需要使用它们。
为了避免反复打开和关闭文件,我试着测试文件句柄是否存在,如果存在,就写入它。如果不存在,就打开它,写入它,然后如果再次出现相同的值,就再次使用它。
我的脚本失败了,出现了以下错误:

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;


我似乎找不到这个问题的答案。我发现的所有问题都是关于测试文件是否存在.
任何帮助将不胜感激.我不是一个程序员,所以要温柔!:-)

hec6srdp

hec6srdp1#

我的脚本由于这些错误而失败
你的论点倒过来了。

print "$line \n" $filehandle;

字符串

print $filehandle "$line \n";


然后,如果再次出现相同的值,则再次使用它。
我会使用一个散列来存储打开的文件句柄(以文件名为键)。
请记住,一个进程可以打开的文件句柄的数量是有限制的。

相关问题