Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Re: Automatic Loop Counter not in perl

by duff (Parson)
on Aug 21, 2007 at 14:19 UTC ( #634093=note: print w/replies, xml ) Need Help??

in reply to Automatic Loop Counter not in perl

I like Perl 6's mechanism:

for @array.kv -> $i, $v { print "Item at index $i has value $v\n"; }

If only there were a way to incorporate it into Perl 5. Maybe I should add that to the wish list for perl 5.12

Replies are listed 'Best First'.
Re^2: Automatic Loop Counter not in perl
by moritz (Cardinal) on Aug 22, 2007 at 08:33 UTC
    Yes, Perl 6's solution is rather generic.

    A loop counter can easily be done like this:

    for @array Z (0..*) -> $item, $count { say "$item occured at position $count"; }

    An array is (lazily) zipped with a (lazy) infinite array (1, 2, 3 Z 'a', 'b', 'c' evaluates to (1, 'a'), (2, 'b', (3, 'c'), in list context it is flattened (1, 'a', 2, 'b', 3, 'c') and the two loop variables eat up two elements per iteration.

    Note that

    • It is not much to type
    • the counter is scoped to the loop block
    • you can easily and intuitivly set the lower boundary of the counter
    • you can choose arbitrary for the counter
    • You only do that when you really need a counter, so no runtime penalties for loops without counter
    • You can omit the ->$item, $counter part and use self declaring parameters with the ^ twigil to save typing

    Hooray for Perl 6!

Re^2: Automatic Loop Counter not in perl
by princepawn (Parson) on Aug 21, 2007 at 17:19 UTC
    Why dont you implement an iterator similar to Python's enumerate() function?

    Carter's compass: I know I'm on the right track when by deleting something, I'm adding functionality

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://634093]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (3)
As of 2021-10-23 23:53 GMT
Find Nodes?
    Voting Booth?
    My first memorable Perl project was:

    Results (88 votes). Check out past polls.