Loops #3

#0 | #1 | #2 | #3 | #4

foreach

We have seen the foreach loop structure when talking about arrays and strings, so we will only briefly cover it here.

An important thing to remember is that $_ is the default variable when looping over ANY kind of list.


my @a = (1,2,3);
foreach $_ (@a) {
    print "$_: I told you this would work.\n";
}

Above it is used explicitly ...

And here it is used implicitly.

foreach (@a) {
    print "And this too.\n";
}

next, last

I'm sure you can imagine a situation where an error may occur in the middle of a loop, or a particular condition exists that you might want to avoid. For this we can use the next command.

It immediately jumps to the next iteration of the loop, skipping the statements following it in the loop.

my @a = (1,2,3);
foreach $_ (@a) {
    next if $_ == 2;
    print "$_: What happened here?\n";
}


my @a = (1,2,3);
foreach $_ (@a) {
    last if $_ == 2;
    print "$_: What's going on?\n";
}

last is used in a loop if a fatal error occurs, as in reaching the end of a file. This is similar to the C break statement. It exits the current loop immediately.