You have to be careful here, because you are doing exactly the same thing. The foreach statement is also accessing <FB> in array context and is reading the whole file into an anonymous array and then iterating over it. You have to use a while loop for this to work correctly.

Try out the following bit of code to test this:

use Benchmark; timethese(1, { 'Trial1 While' => sub { open (FILE, "file2") or die "Can't open file: $!\n"; while (<FILE>) { last; # read one line and exit } close FILE; }, 'Trial2 Foreach' => sub { open (FILE, "file1") or die "Can't open file: $!\n"; foreach my $line (<FILE>) { last; # read one line and exit } close FILE; }, });

Make sure that file1 and file2 are identical (I used two files so that we know there is no caching going on), and that they are large text files. I got the following results with 2 50Meg files:

Benchmark: timing 1 iterations of Trial1 While, Trial2 Foreach... Trial1 While: 0 wallclock secs ( 0.00 usr + 0.00 sys = 0.00 CPU) Trial2 Foreach: 17 wallclock secs (10.77 usr + 1.56 sys = 12.33 CPU) +@ 0.08/s (n=1)

In reply to Re: Re: Reading from file, not to memory by cees
in thread Reading from file, not to memory by FireBird34

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.