Perl logo

Perl Refreshments ⌘

Loops #3 - 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.

To understand this a little better imagine this.
Someone comes up to you and says "It's a holiday!"
What is the 'It' referring to?

In this case, 'It' is referring to today obviously. Even though no date was specified.

In certain loop situations, we don't need a name for what we are referring to. We can use $_ as an alias, the same as 'It' above referred to today.

A caveat: $_ requires a while loop.


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.

Finding your way around with a map


-30-