I ran into this while debugging a fellow programmers code. Took a bit to realize the problem and was wondering if this is an expected situation...

When calling a subroutine/function from within a loop, if we call 'next' within that function (outside of a looping construct itself), it actually iterates the loop of the calling scope rather than issuing an error. Code example:

use strict; my @stuff = (1, 2, 3, 4, 5); foreach my $s (@stuff) { test($s); print "past\n"; } sub test { my ( $s ) = @_; if ($s == 3) { next; #note that this is not within a loop in the #scope of the subroutine } else { print $s . "\n"; } }

What I would expect is that I get a compile time error similar to if I attempted to call next outside a loop. Instead what I get is:

1 past 2 past 4 past 5 past

This shows that the subroutine is actually iterating the last loop, independent of the scope.

My opinion is on the fence on whether I like this result or not...but I do find it unexpected. I assumed that the actions within a subroutine is in its own scope and would not be able to affect the outer loop of a calling scope.

The functionality makes it seem as if the batch of the sub is 'imported' into the process, retaining the scope of the batch for variables but not for things like looping constructs.

Thoughts?

Thanks,

steve

In reply to Loop controls transcends scope? by smsiebe

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.