http://www.perlmonks.org?node_id=36572

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 japhy (Canon) on Oct 13, 2000 at 16:56 UTC
    I wish you'd use a description... what's with the "no while loop" idea? I mean, you can do:
    @lines = <FILE>;
    but that's potentially silly and memory-hogging.

    Originally posted as a Categorized Answer.

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);
Re: How else can I read from a file without using a while loop, testing for the EOF?
by tye (Sage) on Oct 14, 2000 at 08:56 UTC

    Oh, but the looping and checking for EOF is the trivial part. I hate the open()ing, checking for [and properly reporting] failure, and close()ing part.

    my @lines; { local( @ARGV )= $filename; @lines= <>; }

        - tye

    Originally posted as a Categorized Answer.