Statement modifiers in Perl
The postfix forms that put if, unless, and for after the statement they guard.
use strict;
use warnings;
my @temps = (18, 21, 35, 12);
# the condition rides behind the statement it guards
print "heat warning\n" if $temps[2] > 30;
print "cold snap\n" unless $temps[3] > 15;
print "$_ degrees\n" for @temps;
my $sum = 0;
$sum += $_ for @temps;
print "average ", $sum / @temps, "\n";
How it works
print ... ifandunlessguard a single statement with no braces at all.- Postfix
for @tempsruns the statement once per element, with$_as the value. $sum / @tempsputs the array in scalar context, so it divides by the count.
Keywords and builtins used here
forifmyprintunlessuse
The run, in numbers
- Lines
- 13
- Characters to type
- 304
- Tokens
- 75
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 56 seconds.
Step 3 of 3 in Control flow, step 6 of 27 in Language basics.