in reply to next'ing out of a "foreach" loop within a subroutine

"Is there a way to get the "foreach" loop to go to the next array element from within the subroutine?"

Whether this is possible is irrelevant, as this is a bad idea any way. It is a bad idea as it breaks the modulization.

In your demo code, that next is useless any way.

By the way, your routine never took the parameter passed in.

Just to tame your curiosity, try this for once, but never use it in your real code:

use strict; use warnings; my @array = (9 .. 11); foreach my $row (@array) { &routine($row); } sub routine { my $row = shift; if ($row != 10) { print "stuff"; } else { last; } }

This prints only one "stuff", so that that last actually ended the foreach loop.

Replies are listed 'Best First'.
Re^2: next'ing out of a "foreach" loop within a subroutine
by awohld (Hermit) on Oct 30, 2005 at 04:19 UTC
    Yes, I see why it's a bad idea.

    So the "last" ends the foreach loop since a subroutine returns by default the result of the last operation right?
      "So the "last" ends the foreach loop since a subroutine returns by default the result of the last operation right?"

      The result of the last operation is not the last operation, right? So this does not provide an answer.

      If the last statement comes without a LABEL, it ends the innermost enclosing loop. Semantically, a sub is a block, and in the demo code, the innermost enclosing loop is that foreach loop.

      It is just the way the language was designed. You can argue that this should never happen, and the last statement inside a sub should not impact any loop outside the sub.

      So the "last" ends the foreach loop since a subroutine returns by default the result of the last operation right?
      No. If you use next or last to exit a subroutine, the subroutine doesn't return a value; the next code to execute will a new iteration of the loop or the code after the loop, not the code receiving whatever the sub would have returned if it had returned.