in reply to foreach to for

Think lists and iterators. The length may not ever be evaluated in Perl - it's more complicated than that, and you don't need to know. :)

Take a trawl through the STL and you will find equivelent constructs to foreach: for_each in <algorithm> for example.

Update: just to make it a little clearer - Perl generates the list for the foreach "up front" before the first iteration of the loop. If your loop is over an array, the list is the array. If the loop is over something like keys of a hash or lines of a file a temporary list is generated.


DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: foreach to for
by Limbic~Region (Chancellor) on Jun 18, 2006 at 23:18 UTC
    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

      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