Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Automatically exiting a file within a block

by stevieb (Canon)
on Jun 23, 2019 at 18:26 UTC ( #11101774=note: print w/replies, xml ) Need Help??


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.

Replies are listed 'Best First'.
Re^2: Automatically exiting a file within a block
by ikegami (Pope) on Jun 26, 2019 at 08:22 UTC

    I don't know if that's the case of Python, but C# uses a structure like the OP presented because it ensures timely destruction of the object.

    This isn't needed in Perl because Perl's garbage collector ensures that objects are destroyed as soon as they are no longer referenced. (Well, before the start of the next statement after the one in which they cease being referenced, anyway.)

    While this leads to simpler code in Perl, the C# (and maybe Python) approach is faster and can handle references cycles.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11101774]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (8)
As of 2020-06-01 17:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you really want to know if there is extraterrestrial life?



    Results (6 votes). Check out past polls.

    Notices?