Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re^2: Opening a file in Perl

by jcb (Parson)
on Aug 14, 2020 at 23:29 UTC ( [id://11120754]=note: print w/replies, xml ) Need Help??


in reply to Re: Opening a file in Perl
in thread Opening a file in Perl

The major difference here is that, where Python uses explicit magic, Perl uses garbage collection. Perl's reference counting garbage collector is extremely efficient, even though it leaks memory with reference cycles. As a result, not only is open my $fh, ... more efficient, with no extra runtime magic to support a filehandle upon entering the block, it is also possible to pass $fh as a return value or store it in some structure such that it will outlast the scope in which it was opened. Garbage collection means that lexical and dynamic scopes are independent.

The with open(...) as fh: construct in Python is shorthand for a try/finally block that ensures fh is closed when execution leaves the block. Perl is far more flexible here: files are closed explicitly with close or implicitly when their handles are garbage-collected. (This is why bareword filehandles must be explicitly closed: package variables remain in-scope until the interpreter exits.)

Again, in Perl filehandles remain open (unless explicitly closed) as long as references to them exist, while the Python with open(...) as fh: construct limits both the lexical and dynamic extent of the filehandle.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2024-04-16 17:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found