Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Using next inappropriately inside a sub

by Sandy (Curate)
on Mar 29, 2006 at 01:37 UTC ( [id://539846]=perlmeditation: print w/replies, xml ) Need Help??

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlmeditation [id://539846]
Approved by xdg
Front-paged by Courage
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (2)
As of 2024-04-20 03:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found