blahblah has asked for the wisdom of the Perl Monks concerning the following question:

Hello,
The recommended idiom for initiating a strict-safe upload using CGI.pm is:

$fh = $query->upload('uploaded_file'); while (<$fh>) { print; }

In this code the filehandle is never closed. In my specific case I have code to upload many files at once, where all the filename fields are the same in the html form:

my @filehandles = $query->upload('filename'); foreach my $fh (@filehandles) { if (defined($fh)) { while (<$fh>) { print; # or write it out locally } } }

Does this leave me with a whole slew of open filehandles sitting around, or is there some magic happening that closes these filehandles that I'm not seeing?

Thanks,
Alex

Replies are listed 'Best First'.
Re: upload filehandle expiration
by fglock (Vicar) on May 23, 2003 at 17:37 UTC

    The filehandles are closed either at the end of the script, or when you open them again. Or when you leave the scope where the filehandles were defined, which seems to be your case.

Re: upload filehandle expiration
by BrowserUk (Patriarch) on May 23, 2003 at 19:01 UTC

    If your code snippet above is not in a subroutine or otherwise nested in a block, the array of filehandles will not become available for garbage collection until the end of the script.

    If you want to close them earlier, you could either wrap a bare block around the snippet and let the GC take care of them or you could just loop of the array nad close them yourself.

    close $_ for @filehandles;


    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller
Re: upload filehandle expiration
by little (Curate) on May 24, 2003 at 10:41 UTC

    two things...
    CGI.pm will handle the file upload for you. It will check for the max allowed filesize which you can also set ( see Ovid's great CGI-course for that). It will if the file does not exceed the allowed size put it to a tmp directory from where you don't grab it but rather get it passed from CGI.pm.
    Inside your script you are creating ONE filehandle $fh. It is only referenced to inside the scope of your foreach loop. With every run it gets a new upload file associated with. Once you leave your foreach it is out of scope , the $fh is not referenced anymore and will be cleaned up by perls garbage collection.

    Have a nice day
    All decision is left to your taste