http://qs321.pair.com?node_id=1187055


in reply to A way to report open file handles a Perl script has open?

If I'm opening multiple files in a way that might lead to a leak (that is, a dynamic number of them rather than bespoke input/output file handles for an operation) then I keep track of related ones in a data aggregate. An array of file handles or a hash of descriptive keys with values that are file handles makes keeping information about them in one place more simple.

If you're using different file paths or have different IP hosts connecting to your sockets, perhaps a hash like this would be helpful.:

while ( readdir $dirhandle ) { if ( -f $_ ) { if ( open $file{ $_ }, '<', $_ ) { warn sprintf q{I have %d files open from the working direc +tory.}, scalar keys %file; # do stuff } else { delete $files{ $_ }; # report error } } } my @files = keys %file; for ( @files ) { # do something that for some reason requires all the files in the +directory open at once } for ( @files ) { close $file{ $_ }; delete $file{ $_ }; }

The easy solution is to explicitly close file handles as soon as your code is done with them or to open them as lexical handles. If you need to keep multiple file handles open over long periods, close them when you're done with them. Using a hash, you can easily delete the keys for files you no longer need after they're closed, too. Using an array you can shift or pop them if they're closed in array order or use splice. An array or hash and the associated item counts for those structures are easy ways to keep track of things.

I have to wonder, how are you storing your file handles in a way that you can't readily know how many you have open? Are you dynamically creating symbolic scalars for file handles? Don't do that. Are you storing them in arrays or hashes and just never closing them?