Thanks everyone for your replies! :-) For completeness, here are some slurping examples, incorporating various suggestions:
- The basic version (with the improved error message first suggested by haj):
my $data = do { open my $fh, '<', $file or die "$file: $!";
local $/; <$fh> };
- Opening a file with an encoding (in this case UTF-8):
my $data = do { open my $fh, '<:raw:encoding(UTF-8)', $file
or die "$file: $!"; local $/; <$fh> };
- A version that should use less memory, suggested by BrowserUk (see this discussion - Copy-On-Write, available in newer Perls, may take care of this):
my $data; { open my $fh, '<', $file or die "$file: $!";
local $/; $data = <$fh> };
- This short version, first suggested by tybalt89, however, note that as opposed to the above examples, this does not die but only emits a warning if the file could not be opened (unless FATAL warnings are in effect, the minimum needed is use warnings FATAL=>'inplace';; Update: fixed as per choroba's reply, thanks!):
my $data = do { local (*ARGV,$/); @ARGV=$file; <> };
Minor edits for clarity.
Update 2: Actually, I made a mistake in the last example when I first fixed it, it is now tested and correct.
-
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.
|