Re: fancy sorting



Dan Lyke said:
It's my impression that

   for my $i (0..65535)

will create a 65536 element list before iterating $i through it. If
that's the case, why prefer that form over the C style?

perl actually optimizes that specific structure to avoid creating the huge list.

Quoting perlop(1):

       Range Operators

       Binary ".." is the range operator, which is really two different opera-
       tors depending on the context.  In list context, it returns a list of
       values counting (up by ones) from the left value to the right value.
       If the left value is greater than the right value then it returns the
       empty list.  The range operator is useful for writing "foreach (1..10)"
       loops and for doing slice operations on arrays. In the current imple-
       mentation, no temporary array is created when the range operator is
       used as the expression in "foreach" loops, but older versions of Perl
       might burn a lot of memory when you write something like this:

           for (1 .. 1_000_000) {
               # code
           }


-- 
muppet <scott at asofyet dot org>



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]