Looping with Arrays - The "foreach" Loop
- Looping through each item of a list (array) is such a common
programming job that Perl has a special loop mechanism to handle it: foreach
- Example:
#!perl
@dogs = qw(Opie Lassie Baxter Foonman Chaico);
foreach $dog (@dogs) {
print "Nice $dog!\n";
}
- And now is as good a time as any to discuss Perl's weird (and
very useful) "default" variable: $_
- Let's discuss:
#!perl
@dogs = qw(Opie Lassie Baxter Foonman Chaico);
foreach (@dogs) {
print "Nice $_\n";
}
- Or for that matter, the more mysterious:
#!perl
@dogs = qw(Opie Lassie Baxter Foonman Chaico);
foreach (@dogs) {
print;
print "\n";
}