Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Opening a file in Perl

by aartist (Pilgrim)
on Aug 14, 2020 at 19:06 UTC ( [id://11120738]=perlquestion: print w/replies, xml ) Need Help??

aartist has asked for the wisdom of the Perl Monks concerning the following question:

What is Perl equivalent of this python code ?
with open("welcome.txt") as file: 
There is a context manager magic to handle failure in python. How to achieve similar thing in Perl ?

Replies are listed 'Best First'.
Re: Opening a file in Perl
by pryrt (Abbot) on Aug 14, 2020 at 19:42 UTC
    use warnings; use strict; use autodie; # this is the "magic to handle failure" of open ... { open my $fh, '<', 'welcome.txt'; ... } # auto closes file handle when $fh goes out of context ...

      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.

Re: Opening a file in Perl
by stevieb (Canon) on Aug 14, 2020 at 20:36 UTC

    Python:

    with open("welcome.txt") as file: ... # do stuff

    Perl:

    { # can be any block; sub, named or just empty open my $fh, 'welcome.txt' or die "couldn't open file!: $!"; ... # do stuff } # file is auto-closed here
    "There is a context manager magic to handle failure in python."

    Python isn't as 'scope context sensitive' as Perl is in some regards. In Python, the "with" context is no more than a block encapsulated within braces in Perl. Essentially, in Python, the "with" signifies what is called a 'block' or 'scope' in Perl. It simply means everything indented underneath of this "with" will be automatically garbage collected/files closed when the block (ie. context) exits (in basic usage).

Re: Opening a file in Perl
by perlfan (Vicar) on Aug 15, 2020 at 07:18 UTC
    There is no need to complicate this with a block scope* in the Perl example, it's simply:
    open my $fh, '<', 'welcome.txt';
    Regardless of the difference in scoping between Python and Perl, the file handle $fh is closed whenever the variable goes out of scope. For more information on the subject, peruse open and perlopentut. Note the 3 parameter open idiom. open has default behavior, but there's been a move in recent years to be explicit and to also move way from bareword filehandles - i.e., my $fh versus FH.

    Adding a die will allow you to invoke exception semantics. This can often be used as a way to avoid having to do a if file exists check with -e before attempting to open an existing file for reading, for example:

    open my $fh, '<', 'welcome.txt' or die "couldn't open file for reading +!: $!";

    * Scoping in Perl is generally easy to explain, but there's a lot to it. See documention on my, our, and perlsub as a good start.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11120738]
Approved by haukex
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

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

    No recent polls found