foreach loops in Perl
Three foreach shapes: walking a list, counting a range, and editing in place.
use strict;
use warnings;
my @langs = ("perl", "ruby", "go");
foreach my $lang (@langs) {
print uc($lang), "\n";
}
foreach my $n (1 .. 3) {
print "square of $n is ", $n * $n, "\n";
}
# the loop variable aliases the list, so writes reach the array
my @nums = (1, 2, 3);
foreach my $n (@nums) {
$n *= 10;
}
print "@nums\n";
How it works
foreach my $lang (@langs)scopes the loop variable to the loop;ucshouts it.- The
1 .. 3range operator counts upward with no index bookkeeping. - The loop variable aliases the list, so
$n *= 10writes through to@nums.
Keywords and builtins used here
foreachmyprintucuse
The run, in numbers
- Lines
- 18
- Characters to type
- 324
- Tokens
- 90
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 72 seconds.
Step 2 of 3 in Control flow, step 5 of 27 in Language basics.