Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Automatically exiting a file within a block

by davido (Cardinal)
on Jun 23, 2019 at 18:31 UTC ( [id://11101775]=note: print w/replies, xml ) Need Help??


in reply to Automatically exiting a file within a block

Even more lexically constrained:

print do {use autodie; open my $fh, '<', 'test.txt'; local $/ = undef; + <$fh>};

The do {...} block forms a lexical scope. When the block exits, do returns the value of the last expression to execute. So in this case that expression is <$fh>, which reads the contents of the file opened with the $fh file handle. Then when the block terminates the lexical scope closes and $fh falls out of scope. When that happens, the file is closed.

The use of autodie provides basic exceptions around the file IO operations, again constrained to the narrow lexical scope of the do {...} block.

The nice thing that Python is providing here is a form of topicalization (for lack if me thinking up a better word). The with statement is creating that lexical scope, in a way, and topicalizing the file handle as f. Perl's native open doesn't return the handle; instead, it modifies its first arg to contain the handle. So it is inconvenient to come up with a proper Perl alternative that follows the same structure. But it's still possible using IO::File:

use IO::File; for my $fh (IO::File->new('foo', 'r')) { print $fh->getlines; } # $fh->close is unnecessary.

Here we're using for to topicalize the filehandle similar to what happens when with is used in Python.

Even more tersely:

use IO::File; print $_->getlines for IO::File->new('foo', 'r');

Dave

Log In?
Username:
Password:

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

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

    No recent polls found