Due to my own bad coding, I have discovered another

Gotcha

(or maybe a 'got-me'?) that jumped up and bit me.

Of course, if I had had warnings on... it would have been simpler to see what was going on, ... but then on the other hand, I would not have seen this fun stuff:

#!/usr/bin/perl use strict; #use warnings; for my $i (1 .. 20) { isodd($i); print "$i\n"; } sub isodd { my $i = shift; next if int($i/2)*2 == $i; return; }

gives:

1 3 5 7 9 11 13 15 17 19

Perl is so cool, but so dangerous without warnings!

Needless to say, after some refactoring, my 'next' was in a different module than my loop, and I couldn't figure out why bits of code were not being executed as expected.

Replies are listed 'Best First'.
Re: Using next inappropriately inside a sub
by roboticus (Chancellor) on Mar 29, 2006 at 02:07 UTC
    Sandy--

    That's gotta be the funniest/scariest thing I've seen in Perl to date. Thank goodness "use warnings" picks it up.

    --roboticus

Re: Using next inappropriately inside a sub
by DrHyde (Prior) on Mar 29, 2006 at 09:45 UTC
    Cool! I wonder if it leaves bogus stuff on the call stack. And if after you've nexted, a return inside the for loop would go all freaky.
      I wonder if it leaves bogus stuff on the call stack

      No, it is a supported feature.

        I agree. I use this feature in cgrep (see the nextfile function). The only problem with it is that loop labels are (lexically scoped, not dynamically) dynamically scoped, not lexically, so you can never make sure that your loop labels don't accidentally clash with those of a function you call from another module.

        Update: see also Re: How can I return to main loop, not to caller?, and Re: Perl etiquette - eval.