Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>For most purposes, you probably won't notice a difference. However, <code>foreach</code> reads each line into a <strong>list</strong> (<a href="http://perldoc.perl.org/perlfaq4.html#What-is-the-difference-between-a-list-and-an-array%3f" rel="noreferrer">not an array</a>) before going through it line by line, whereas <code>while</code> reads one line at a time. As <code>foreach</code> will use more memory and require processing time upfront, it is generally recommended to use <code>while</code> to iterate through lines of a file.</p> <p>EDIT (via Schwern): The <code>foreach</code> loop is equivalent to this:</p> <pre><code>my @lines = &lt;$fh&gt;; for my $line (@lines) { ... } </code></pre> <p>It's unfortunate that Perl doesn't optimize this special case as it does with the range operator (<code>1..10</code>).</p> <p>For example, if I read /usr/share/dict/words with a <code>for</code> loop and a <code>while</code> loop and have them sleep when they're done I can use <code>ps</code> to see how much memory the process is consuming. As a control I've included a program that opens the file but does nothing with it.</p> <pre><code>USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND schwern 73019 0.0 1.6 625552 33688 s000 S 2:47PM 0:00.24 perl -wle open my $fh, shift; for(&lt;$fh&gt;) { 1 } print "Done"; sleep 999 /usr/share/dict/words schwern 73018 0.0 0.1 601096 1236 s000 S 2:46PM 0:00.09 perl -wle open my $fh, shift; while(&lt;$fh&gt;) { 1 } print "Done"; sleep 999 /usr/share/dict/words schwern 73081 0.0 0.1 601096 1168 s000 S 2:55PM 0:00.00 perl -wle open my $fh, shift; print "Done"; sleep 999 /usr/share/dict/words </code></pre> <p>The <code>for</code> program is consuming almost 32 megs of real memory (the <code>RSS</code> column) to store the contents of my 2.4 meg /usr/share/dict/words. The <code>while</code> loop only stores one line at a time consuming just 70k for line buffering.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload