Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

How else can I read from a file without using a while loop, testing for the EOF?

by Anonymous Monk
on Oct 13, 2000 at 16:41 UTC ( #36572=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question: (files)

How else can I read from a file without using a while loop, testing for the EOF?

Originally posted as a Categorized Question.

  • Comment on How else can I read from a file without using a while loop, testing for the EOF?

Replies are listed 'Best First'.
Re: How else can I read from a file without using a while loop, testing for the EOF?
by S@nto (Initiate) on Apr 23, 2006 at 17:53 UTC
    Much less dangerous than undef-ing $/ globably (and maybe forgetting to set it back) local-ize it to a block that just does your file reading:
    my $string = do{ local $/; <$filehandle> };
    Or you can use $RS if you can't (or don't want to) remember $/.
      I like the slurp method provided by IO::All:
      use IO::All; my @lines = io('file.txt')->slurp;
Re: How else can I read from a file without using a while loop, testing for the EOF?
by Fastolfe (Vicar) on Oct 13, 2000 at 22:05 UTC
    A while (<FH>) { ... } block implicitely tests for eof. Are you trying to avoid the <FH> construct (which reads line-by-line, unless you've undefined $/ as mentioned by another poster), such as with binary files?

    There are also the very standard and documented built-ins: read and sysread. These will read an arbitrary amount of data from a file.

Re: How else can I read from a file without using a while loop, testing for the EOF?
by ickiller (Novice) on Oct 13, 2000 at 20:38 UTC
    As i know, the most efficient method is to set the input record separator to nothing like the following snippet:

    $/ = undef; $wholefile = <FILE>;
    Roli
Re: How else can I read from a file without using a while loop, testing for the EOF?
by t0j0 (Novice) on Oct 14, 2000 at 05:22 UTC
    or maybe you can use file-slurp function..
    use File::Slurp; # to get your data into scalar variable $output_string = read_file($filename); # or this to get your data into array @output_array = read_file($filename);

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://36572]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2021-04-20 05:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?