Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

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.

In reply to Re: Any downsides to this slurp idiom? (updated) by haukex
in thread Any downsides to this slurp idiom? by haukex

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?

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (2)
As of 2023-03-26 09:30 GMT
Find Nodes?
    Voting Booth?
    Which type of climate do you prefer to live in?

    Results (63 votes). Check out past polls.