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:
Kent Fredric
Date:
November 28, 2016 07:14
Subject:
Re: [perl #130038] Builtin variable for loop index in foreach
Message ID:
CAATnKFCQyJhTAz5NHgiEzimf_mkiv8tEA4DbYXbXs+mTzkCS2A@mail.gmail.com
On 28 November 2016 at 13:48, Aristotle Pagaltzis <pagaltzis@gmx.de> 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.

-- 
Kent

KENTNL - https://metacpan.org/author/KENTNL

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