Search code examples
perlif-statementfilehandle

open filehandle if it doesnt exist, use it if it does


I am scanning a file looking for certain values. For each of those values, I want to create an output file and dump the matching line into that specific output file. The values are unknown in advance so as I encounter them, I need to use them.

To keep from opening and closing files over and over, I am trying to test if a filehandle exists and if it does, write to it. If it doesn't, open it, write to it and then use it again later if the same value comes up again.

My script is failing with these errors:

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"

Here's what I have so far...

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;

I can't seem to find an answer on this. All of the questions I find are about testing if a file exists or not... not whether or not the file handle itself exists.

Any help would be appreciated. I'm not a programmer, so be gentle! :-)


Solution

  • My script is failing with these errors

    You have the arguments backwards.

    print "$line \n" $filehandle;
    

    should be

    print $filehandle "$line \n";
    

    then use it again later if the same value comes up again.

    I'd use a hash to store the opened file handles (keyed by file name).

    Keep in mind that that there's a limit on the number of open file handles a process can have.