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

Is there a better way to do this?

A better way, in my opinion, would be to have the return value of routine indicate whether the for loop should move onto the next value.

foreach $row (@array) { next unless routine($row); # more code here } sub routine { if ($row != '10') { print "stuff"; return 1; } else { return 0; } }

A minor issue with your code as posted: You cannot say $row != '10'. You are using numeric equality against a string. The correct technique is to either compare against a number $row != 10 or compare using string equality $row ne '10'.

You can get Perl to help you with looking out for problems like this if you have warnings switched on. To enable them, add a use warnings; somewhere in the file.

• another intruder with the mooring in the heart of the Perl

Replies are listed 'Best First'.
Re^2: next'ing out of a "foreach" loop within a subroutine
by sauoq (Abbot) on Oct 30, 2005 at 21:04 UTC

    Just a nit...

    You cannot say $row != '10'.

    I'd agree it isn't good code, but you can do it; and perl won't complain even with strict and warnings on.

    -sauoq
    "My two cents aren't worth a dime.";