On 8 November 2016 at 11:35, Ed Avis <eda@waniasset.com> wrote: > Dave Mitchell wrote: > >>For ranges, e.g. (1..10) and ('a'..'z'), it only records the current value and the last value. > > But for numeric ranges, if you know the current value it is just a subtraction to find its index. > For string ranges like 'aa'..'zz' it is trickier but still possible. So fetching $# could do that? > >>give $# get magic that searches the context stack for a loop context, >>then retrieves the current loop index stored in there. That wouldn't >>slow down normal loops, but accessing $# itself might be quite slow. > > I think it would still be faster than the equivalent handwritten code using an $i variable, though? > > My concern would be whether in all cases 'searching the context stack for a loop' > gives exactly the same semantics as we currently have for $_ in nested loops. > Or whether the odd differences are not worth worrying about. An alternative would be to introduce a new keyword, say "for_with_index". Then you could say for_with_index (LIST) { } and perl would know it has to do the extra bookkeeping to populate $#. But personally I would not use $#, i would use something like ${^LOOP_INDEX}. YvesThread Previous | Thread Next