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:
demerphq
Date:
November 8, 2016 10:37
Subject:
Re: [perl #130038] Builtin variable for loop index in foreach
Message ID:
CANgJU+Uvp24-CZ_e=6iURzUwKXG5KsqR-L0wg3vwLX=SE+M5zg@mail.gmail.com
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}.

Yves

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