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


in reply to Automatically exiting a file within a block

If you open a file in a block, Perl will close it automatically when the scope of the block finishes:

use warnings; use strict; { open my $fh, '<', 'a.txt' or die $!; # do stuff with file handle } # file handle is closed here # in fact, the $fh isn't even accessible here at all

The block can be a bare block like I've shown, or it could be within a function, loop etc. Essentially, all file handles within any scope will automatically close themselves when the scope they're in finishes. If it's in file scope, it'll close itself when the program exits.