Perl-Sensitive Sunglasses | |
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
Even more lexically constrained:
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:
Here we're using for to topicalize the filehandle similar to what happens when with is used in Python. Even more tersely:
Dave In reply to Re: Automatically exiting a file within a block
by davido
|
|