typestar

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

  1. foreach my $lang (@langs) scopes the loop variable to the loop; uc shouts it.
  2. The 1 .. 3 range operator counts upward with no index bookkeeping.
  3. The loop variable aliases the list, so $n *= 10 writes through to @nums.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Control flow, step 5 of 27 in Language basics.

← Previous Next →

foreach loops in other languages