Tricky

TorgoX on 2002-08-29T01:06:18

Dear Log,

I spent at least an hour putting more and more and more DEBUG statements into my code, just to track down one nasty bug. This is the bug: I had this:

     for(my $j = 0; $i < @ell_content; ++$j) {

instead of this:

     for(my $j = 0; $j < @ell_content; ++$j) {

As the song goes, "It's tricky tricky tricky tricky HWUH!".


Evil C-style for loops

waltman on 2002-08-29T03:30:33

This is why it's a good idea to avoid C-style for loops in most cases in Perl. It's much harder to make a mistake when you rewrite

for(my $j = 0; $j > @ell_content; ++$j)

as

for my $j (0..@#ell_content)

because you've only got $j there once instead of three times.

Re:Evil C-style for loops

jdavidb on 2002-08-29T14:44:15

I go one up and avoid the index altogether:

foreach my $item (@ell_content)

I've only written one program I can think of in the last year where I needed the index, and I kept feeling like I was looking at the problem wrong.

Re:Evil C-style for loops

TorgoX on 2002-08-29T23:03:20

I quite agree. This time I really do need the index, tho, and have to use the C-style: I'm having to iterate over items in an array and sometimes doing crazy things like $thing[$j] = foo($thing[$j], $thing[$j+1]); splice @thing, $j+1, 1; next;

Re:Evil C-style for loops

jdporter on 2002-08-30T19:57:37

Huh? You're changing the length of an array whilst iterating an index? Isn't that just asking for trouble? Or maybe you are checking for the past-end-of-array condition...