On 08/09/2013 04:24 AM, Dermot wrote:
my $counter = 0;
foreach my $e ( a .. z ) {
       $counter++;
       if ( $counter == 5 ) {
            ....
       }
}

I know this is a perl idiom but I, and I suspect others, would find a perl
variable useful for the keeping the count when iterating. The draw back
with the above is that $counter has scope outside of the block and that
seems messy. I am not sure why the C style loop, EG:

for (my $i = 0; $i =< $#items; ++$i)

and the perl idiom for that is:

foreach my $i ( 0 .. $#items ) {}

you rarely need c style loops in perl. foreach loops are simpler, faster, less error prone (off by one errors).
{}

is so unpopular. Probably because it does look nice. It does have the
advantage of keeping all the variables in the immediate block so you don't
need to worry about $counter 100 lines down the code.
A feature request perhaps but I'm sure there are good reasons why the
maintainers haven't added such a perlvar.

it would be difficult to add such a variable as how would it work in nested loops or loops that call subs which have loops?

as someone else posted and few seem to have read, the each() call now will work on arrays too and return the current index and value in each iteration. each used to only work on hashes.

but one final thing, i see using an index loop variable as a flag that the data structure design is weak. that style (like the c loop) are just not perlish. you generally will loop over lists and arrays and just deal with each element.

thanx,

uri


--
Uri Guttman - The Perl Hunter
The Best Perl Jobs, The Best Perl Hackers
http://PerlHunter.com

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to