[ back to toc ]

Break the loop statement

Date: 2002/04/18 10:13

Q:
hi!

i would like to know how to break foreach() statement?

problem : i'm doing foreach statement which have conditional statement
under it. i want to break the foreach statement if the conditional was
satisfied.

eg :

foreach $l(@array) {
if ($l eq 1) {
# break this foreach statement
}
}

thanx.
A:
You were programming C before Perl didn't you. Just I did and even these
days after programming many years of Perl and C parallel I make the
mistake mixing up 'break' and 'last'. The C language 'break' statement in
Perl is called 'last'. Thus your code should look:

foreach $L (@array){
last if $L eq "1";
}

Also note that 'eq' compares two strings. Numerical comparison is == just
like in C.

There is a command called 'next', which is like C 'continue' and there is
also a 'redo'. Read the documentation to see the differences.

Regards,
Peter

[ back to toc ]