Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Automatically exiting a file within a block

by stevieb (Canon)
on Jun 23, 2019 at 18:26 UTC ( [id://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 (Patriarch) 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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11101774]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (7)
As of 2024-04-19 09:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found