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.
In reply to RE: slurp
by btrott
in thread slurp
by Vane
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.