in reply to slurp

I don't have Programming Perl, but I highly doubt that the book advised using that code to slurp a file into a variable, because it doesn't work. :) (Not that technical books are always correct, but this is rather spectacularly incorrect--not to mention incomplete.)

The main problem with this (aside from the fact that it's not complete) is that you've set the input record separator ($/) incorrectly. Setting it to "" tells Perl to read in paragraphs at a time, not the whole file.

To read in the entire file, set $/ to undef. So your sub should look something like this:

sub slurp { local $/ = undef; local *X; open X, $_[0] or die "Can't open $_[0]: $!"; my $slurp = <X>; close X or die "Can't close $_[0]: $!"; $slurp; }
Your other problem, which I've fixed, is that you were using $_, not $_[0].

The code should be used like this:

my $contents = slurp("/home/foo/bar.txt");
The sub will die when it can't open or close the file, so you may want to change that; but you should always check for errors, no matter what.

Replies are listed 'Best First'.
RE: RE: slurp
by Vane (Novice) on Jun 19, 2000 at 10:31 UTC
    there you go, but please, not "spectacularly". That's what happens when you're in a hurry. I slapped it off without running the code. Nevermore. 'incomplete' is expected isn't it? But thanks for the comeuppance. I have shunned $/=undef since perl 4.something, because of an inconsistency then, but it works solidly in 5+. Like a stutter, I find it hard to shake. And, of course, in the example slurp contains nothing when while finishes. Vane --Watch the stars