I have tried every suggestion I could find on how to pull (aka Slurp) the text of a file into a perl program and all of them that say they should work weren't. I am on a Mac Mini with Lion (10.7), and the perl version is 5.12. Here are some that I've tried:

#!/usr/local/env Perl5.12 ### filename:Hello.pl use strict; use File::Slurp; my $string; open (my $QBF, "<QBF.txt"); $string = read_file($QBF); print "\n"; print $string + "\n"; # doesn't print anything. (or prints "0") print "\n";

## -----------------

use File::Slurp; open my $fh, "<", "QBF.txt" or die $!; local $/; # enable localized slurp mode my $content = <$fh>; close $fh; print $content; # doesn't print anything.

At least last night is wasn't working. I had started with a while loop which worked fine by itself:

print"\n"; open (my $QBF, "QBF.txt"); while (<$QBF>) { print; }

after that I was trying to add the other methods for "slurping", into that same program, and it wasn't until I segregated them into two separate files that the second version worked.

use File::Slurp; open my $fh, "<", "QBF.txt" or die $!; local $/; # enable localized slurp mode my $content = <$fh>; close $fh; print $content; # prints now.

So what I'm wondering is if i put these two pieces of code together, is the read pointer already at the end of the file, and that's why they won't work in succession? It seemed like I was only getting one output even though I had two different routines for extracting (one just prints, the other saves the file contents to a local scalar for processing, and then prints.) Also I'd like to know more about what "$/" is and how it works Thanks.


In reply to Contents of a file into a scalar by MarkofPerl

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.