Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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


In reply to Re: Automatically exiting a file within a block by davido
in thread Automatically exiting a file within a block by betmatt

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

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

    No recent polls found