in reply to slurp::file

Maybe I'm just old fashioned (or I'm not paying enough attention), but I don't quite understand why this:
use File::Slurp; # ... my $file_data = read_file( 'file.name' );
is so much better than this:
my $file_data = do { local $/; open(I,'file.name'); <I> };
or why this:
use File::Slurp; #... my @lines = read_file( 'file.name' );
is better than this:
open( I, 'file.name' ); my @lines = <I>;
I realize that the man page for File::Slurp covers a lot more than that, but it doesn't seem as though it really adds all that much in terms of simplifying things that are already pretty easy just using unadorned functions that are already in common use (setting $/, using binmode, etc). And it doesn't seem to help much in terms of providing any extra layer of OS-independence.

So if the previous replies provide what you need in order to install the module, and you really want to do that, then good, go that way and be glad. But if you still have problems trying to use the module, look up the "fundamentals" on the things you really need to do -- it won't be that hard to work out a solution without the using module.

Replies are listed 'Best First'.
Re^2: slurp::file
by xdg (Monsignor) on Jul 26, 2005 at 10:06 UTC

    One reason, I'd imagine, is just simplicity of code reuse -- less chance of miscoding by mistake. However, there are other benefits. There's an extensive article on the topic. For example:

    Excerpt from Perl Slurp Ease by the author of File::Slurp

    Fast Slurping

    Somewhere along the line, I learned about a way to slurp files faster than by setting $/ to undef. The method is very simple, you do a single read call with the size of the file (which the -s operator provides). This bypasses the I/O loop inside perl that checks for EOF and does all sorts of processing. I then decided to experiment and found that sysread is even faster as you would expect. sysread bypasses all of Perl's stdio and reads the file from the kernel buffers directly into a Perl scalar. This is why the slurp code in File::Slurp uses sysopen/sysread/syswrite. All the rest of the code is just to support the various options and data passing techniques.

    That said -- knowing the fundamentals is good too. If I'm just slurping a text file once of a known, manageable size, then using the standard idiom would make sense. But once I'm writing that idiom more than a couple times, I'm going to want to code it as a subroutine -- and that's when I'd rather use File::Slurp rather than roll my own each time.

    -xdg

    Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.