Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Foreach & file io

by Xxaxx (Monk)
on Jun 05, 2001 at 13:53 UTC ( [id://85762]=perlquestion: print w/replies, xml ) Need Help??

Xxaxx has asked for the wisdom of the Perl Monks concerning the following question:

With your help I'd like to double check my understanding of how foreac works with file io.

foreach my $line (<$INFILE>) { ## do stuff }
As far as I know the above snippet will read a single line at a time during processing.

I'm guess I'm just checking to make sure it doesn't try reading the whole file into a temporary array and then feed the array elements to the foreach.

Is that correct? Claude

Replies are listed 'Best First'.
Re: Foreach & file io
by jeroenes (Priest) on Jun 05, 2001 at 14:00 UTC
    It all depends on what you did to $/, see perlvar. If you leave that alone, your script always will read single lines with the  for my $line (<INFILE>) or my $line=<INFILE>; syntax.

    Beware, though, that fileGLOBs are written as  open IN, $file;. Your $INFILE will work on a variable, that's not what you (probably) want.

    (Update Unless you pass a reference to a fileGLOB :-). I would use lowercase here though, to take away possible confusion with real fileGLOBs and constants. Try $fh_infile, eg.)

    Cheers,

    Jeroen
    "We are not alone"(FZ)

      Thanks the perlvar was the piece that solved the puzzle.
      Seems like no matter how many times I read that thing I only remember the stuff I have a need for before I read it.

      Thanks again
      Claude

      p.s. the $INFILE is actually correct since I'm opening my file in a subroutine then returning *FH.

(tye)Re: Foreach & file io
by tye (Sage) on Jun 05, 2001 at 19:10 UTC

    By default, <> will read one line at a time. However, foreach builds up the list before iterating over it so the above code will read the entire file into memory and then start iterating over the lines.

    For this type of thing you are much better off using while.

            - tye (but my friends call me "Tye")
      Thanks tye,
      Based on the program's timing that is what it felt like. Hence checking with fell monks for the scoop. Much appreciated.

      Back to the while.
      Claude

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2024-04-24 16:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found