Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Automatic Loop Counter not in perl

by duff (Parson)
on Aug 21, 2007 at 14:19 UTC ( [id://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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (7)
As of 2024-04-19 09:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found