in reply to foreach question

Good question. foreach my $line(<INFILE>){} reads the entire file into an anonymous array, aliasing each element in turn to $line. while (my $line = <INFILE>){} reads the file one line at a time, storing each in turn in $line.

The foreach version must allocate more memory than the while loop, which is a bit slower. The tradeoff is up to you.

Update: ++chromatic points out that foreach iterates over a list, not an anonymous array.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re: Re: foreach question
by glwtta (Hermit) on Feb 25, 2003 at 02:56 UTC
    Thanks, I suspected as much, but wanted to make sure. In the code, the loop actually just appends $line to a string, so I suspect the effect of the foreach is not what the author had in mind.
      That's what people call a 'slurp'. There's many ways to do it and if you search PerlMonks for 'slurp' you'll find them. Here's one I cooked up earlier:
      # FILE is already open ... { local $/ = undef; $slurp = <FILE>; }
      Much better (and faster) than using joins, or loops to append. Keep it inside the {} block so that the change to $/ is only temporary. (also see $/ at perldoc). The file's entire content ends up in $slurp.