develooper Front page | perl.perl5.porters | Postings from November 2016

Re: [perl #130038] Builtin variable for loop index in foreach

Thread Previous | Thread Next
From:
Dave Mitchell
Date:
November 8, 2016 10:26
Subject:
Re: [perl #130038] Builtin variable for loop index in foreach
Message ID:
20161108102615.GC3081@iabyn.com
On Mon, Nov 07, 2016 at 03:46:12AM -0800, Ed Avis wrote:
> I was wondering, if perl knows internally how far along in @things we
> are, perhaps it could expose that list index to the programmer?

Currently perl doesn't always know the index. For ranges, e.g. (1..10) and
('a'..'z'), it only records the current value and the last value.
Recording the index for these cases would involve adding an extra field to
the loop part of the context union, which might increase the size of the
context struct; also it would require extra bookkeeping work for each loop
iteration.

> Suppose that the currently unused $# variable were used for this.

If we did this this, we would have to either:

* update $# on each loop iteration, which would slow down all loop
  iterations, or
* 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.

-- 
My Dad used to say 'always fight fire with fire', which is probably why
he got thrown out of the fire brigade.

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About