Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: A way to report open file handles a Perl script has open?

by mr_mischief (Monsignor)
on Apr 05, 2017 at 00:26 UTC ( #1187055=note: print w/replies, xml ) Need Help??


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?

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1187055]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (7)
As of 2018-02-23 13:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    When it is dark outside I am happiest to see ...














    Results (302 votes). Check out past polls.

    Notices?