The reason your second block of code isn't used more is because it is much slower. On small amounts of data, you won't notice, but on larger ones you will. Why?

In the top block of code, perl knows to just read, as fast as reasonable, the entire contents of a file and store it to a variable.

In the lower block of code, it must read one line at a time (which takes longer, partly because there must be a check for line endings). Then, it must join those lines into a string before returning. That's a lot of extra steps.

Actually, your "standard" way of slurping is less than ideal as well, since you are copying the string when your function returns. Why not:

my $content; { local $/ = undef; open my $fh, $_[0] or die "Can't open $_[0]: $!"; $content = <$fh>; }

Or, if it really must be abstracted into a sub, pass around a reference?

sub slurp { local $/ = undef; open my $fh, $_[0] or die "Can't open $_[0]: $!"; my $slurp = <$fh>; return \$slurp; } my $content = slurp('filename'); print $$content;

Of course, you could avoid all this re-inventing of the wheel and just use Slurp:

use Slurp; my $content = slurp('filename');
<-radiant.matrix->
A collection of thoughts and links from the minds of geeks
The Code that can be seen is not the true Code
"In any sufficiently large group of people, most are idiots" - Kaa's Law

In reply to Re: slurp mode by radiantmatrix
in thread slurp mode by szabgab

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.