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

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

Thread Previous | Thread Next
Kent Fredric
November 28, 2016 07:14
Re: [perl #130038] Builtin variable for loop index in foreach
Message ID:
On 28 November 2016 at 13:48, Aristotle Pagaltzis <> wrote:
>> * 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.

There's a third option, its not well employed, but it could be:

At parse time, the Perl compiler parsing the for { } block *lexically*
parses for a variable ( we'll just say $# for now ).

And then upon detecting that variable's usage in its block, then instruments
the for loop to behave differently.

This would mean *no* performance impact for existing code at runtime,
and the associations of loops and variables would be compile-time bound.

Though it could be tricky.

for ( ... ) {
   for ( ... ) {

Here $# is only instrumenting its direct parent.

Logically, it would be like imagining there was a builtin called
"for_idx" , which looked as follows:

for_idx my($#, $value) ( .... ) {


And I think that latter form is quite easy to reason about.

You don't have to worry about distant subs secretly poking at $# and
sniffing your index and all those kinds of spooky side-effects.

Also, my memory tells me lexicals are rather fast in comparison to
globals, but my memory could be wrong.



Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About