Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Short answer: Almost always, you should open/close <em>only once</em>.</strong> Details below.</p> <p>The decision of whether to do that depends on 4 things:</p> <ol> <li><p>Are there other processes that may need to write to the file?</p> <p>If so, you may need to lock the file, and the good behavior for a process designed for concurrent use is to release the locked shared resource as fast as possible so others can get the lock.</p></li> <li><p>Are there MANY files you need to open?</p> <p>If so, you might run out of file handles with too many open files, so you need to close.</p></li> <li><p>How much tolerance you have for losing data in the file if the program crashes.</p> <p>If you need to save the data from buffer into the file, you need to flush it. This CAN be done by frequently closing, although a better solution is either frequent flushing or autoflush on the file handle being turned on.</p></li> <li><p>Do you care greatly about not being able to close the file after running out of disk space?</p> <p>If so, the more often you close/reopen the file, the less data you will lose due to filesystem being full so whatever you wrote since last <code>open</code> is gone.</p></li> </ol> <p><strong>In any other scenario, only open/close once (well, plus maybe extra close in <code>__DIE__</code> handler and <code>END{}</code> block</strong> (and majority of time, you WILL likely be in other scenarios).</p> <p>That is because opening/closing the file just wastes system resources for no reason whatsoever AND makes your code longer. To be more specific, file open and close are expensive operations, requiring both system calls (that may force jump to kernel from userland), and extra disk IO which is VERY expensive resource wise. To verify that, run some system utilization measurment utility on your OS, and run a Perl script that does nothing except open/close 10000 different file names 100 times each.</p> <p>Please note (regarding scenarios #3/#4) that if you care greatly about not losing any data, <strong>you should not be using file IO in the first place</strong> - use a database or a messaging system with delivery guarantees.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload