typestar

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

  1. print ... if and unless guard a single statement with no braces at all.
  2. Postfix for @temps runs the statement once per element, with $_ as the value.
  3. $sum / @temps puts the array in scalar context, so it divides by the count.

Keywords and builtins used here

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.

Type this snippet

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

← Previous Next →