On Thu, Aug 8, 2013 at 2:05 PM, Unknown User <knowsuperunkn...@gmail.com>wrote:

>
> Hello,
>
>
> If i am iterating through the elements in an array, at any point is it
> possible to say which element i am handling without using a counter? Are
> there any builtins that i can use for it?
>
> ie
> foreach my $element (a..z) {
>    ...
>    if ( i am the 5th element ) { handle me special }
>
> }
>

Not without modifying the code, unfortunately. You could add a counter
variable and increment that each time you pass through the loop.
Alternatively, there's a couple of options, but you'll need to start all of
them by storing that list in an array:

    my @foo = "a".."z";

The usual way people do this is by iterating through the indexes:

    foreach my $i ( 0..$#foo ) {
        say "$i $foo[$i]";
    }

And if you have a non-legacy Perl, you can do this instead:

    use 5.012;
    while ( my ($i, $v) = each(@foo) ) {
        say "$i $v"
    }

Reply via email to