http://www.perlmonks.org?node_id=11101775


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