in reply to Re: foreach to for
in thread foreach to for

GrandFather,
Update: just to make it a little clearer - Perl generates the list for the foreach "up front" before the first iteration of the loop.

Unfortunately, the story is about as clear as mud. In recent Perl's, there are optimizations to avoid generating the entire list up front when and where possible. For instance:

for (1 .. 2_000_000_000) { print "$_\n"; }
You will see by checking memory consumption that the list is not generated.

Cheers - L~R

Replies are listed 'Best First'.
Re^3: foreach to for
by GrandFather (Saint) on Jun 18, 2006 at 23:41 UTC

    Unfortunately, the story is about as clear as mud.

    Agreed. The important point for OP is that it is not clear when or if Perl ever calculates the number of items. In many cases Perl simply doesn't know or care. For OP's purposes when, how or if Perl ever evaluates the number of items is actually irrelevant, but OP hasn't figured that out yet. C++ is a whole different world, but the STL does provide similarly anonymous management of lists.


    DWIM is Perl's answer to Gödel