Perl, lesson 5
Computers are good at doing the same thing many times. Perl has several loops; you will use
foreach and while most of the time.
The range operator .. builds a list of whole numbers, both ends included. foreach (or its
shorter spelling for; they are the same keyword) takes each item in turn:
my $i makes a fresh variable that exists only inside the loop. A range only counts
upward: 3 .. 1 is empty. To count down, reverse the list:
When you need a custom step, Perl also has the three-part loop from C: a start, a condition checked before every pass, and an update after every pass:
while repeats as long as its condition is true. repeats as long as it is false.
2 exercises to try what you just read.
untilThis is one of the most common lines of Perl you'll ever write:
Each pass reads the next line. When the input runs out, <STDIN> returns undef and the
loop ends. Perl quietly checks whether the line is defined rather than true, so a line
containing just 0 doesn't stop the loop by accident.
last leaves the loop immediately (like break in other languages).next skips the rest of this pass and starts the next one (like continue).They pair nicely with postfix conditions:
When loops are nested, last and next affect the innermost one. You can give an outer loop
a label (like ROW:) and write last ROW to leave it instead.
Read a whole number n (0 or more). Print the numbers from n down to 1, one per line, and
then Liftoff!.
Sample input:
Sample output:
Your fitness tracker sends one whole number per line: the steps walked each day. A line
containing 0 marks the end of the data, and anything after it must be ignored. Print how
many days came before the 0, and their total:
Sample input:
Sample output:
for my $i (1 .. 3) {
print "Lap $i\n";
}
# Lap 1
# Lap 2
# Lap 3for my $i (reverse 1 .. 3) {
print "$i "; # 3 2 1
}
print "\n";for (my $i = 0; $i <= 10; $i += 5) {
print "$i "; # 0 5 10
}
print "\n";my $fuel = 10;
while ($fuel > 0) {
print "Fuel: $fuel\n";
$fuel -= 4;
}while (my $line = <STDIN>) {
chomp $line;
print "Got: $line\n";
}for my $n (1 .. 100) {
next if $n % 2; # skip odd numbers
last if $n > 10; # stop after 10
print "$n "; # 2 4 6 8 10
}
print "\n";33
2
1
Liftoff!Days: <count>
Total: <sum>4000
6500
3000
0Days: 3
Total: 13500