Perl, lesson 2
Perl marks every variable with a symbol in front of its name, called a sigil. The sigil
tells you what kind of thing the variable holds. This lesson is about the simplest kind: the
scalar, which holds one value and uses the $ sigil.
my declares a new variable that exists only inside the surrounding block (or file). Under
use strict, using a variable you never declared with my is an error, which catches typos
before they become bugs. Declare each variable once, then assign to it without my.
A scalar can hold a number, a string, or undef (Perl's "no value"). Perl does not make you
pick a type. Instead, it converts values depending on how you use them:
That is why Perl has separate operators for numbers and strings: always adds numbers and always joins strings. You will see the same idea with comparisons in a later lesson.
2 exercises to try what you just read.
+.Numbers can be whole (7), decimal (42.5) or written with underscores for readability
(1_000_000). A variable declared without a value is undef; printing it under
use warnings gives an "uninitialized value" warning.
Inside double quotes, Perl replaces scalar variables with their values. Single quotes leave the text alone:
When a variable name runs into other letters, wrap the name in braces: "${cups}x".
For a value that must never change, use the constant pragma. Constants have no sigil and
are not interpolated in strings, so you print them as separate items:
Variable names use letters, digits and underscores and can't start with a digit. Perl style
favours snake_case: $max_health, $total_price. Names are case sensitive. Constants are
usually written in UPPER_CASE.
Updating a variable based on itself is common enough to have short forms: $x += 5,
$x -= 2, $x *= 3, $x /= 2, and for strings $s .= "more". There is also $x++ to add
one.
The starter declares four values for a game character. Print them on one line in exactly this format, using interpolation in a double-quoted string:
The program reads no input.
Use a scalar $savings that starts at 20. Change it three times and print it after each
step, using the shortcut operators:
Expected output:
use strict;
use warnings;
my $name = "Rowan";
my $level = 7;
$level = $level + 1; # scalars can be reassigned
print "$name is level $level\n"; # Rowan is level 8my $text = "42";
print $text + 8, "\n"; # 50 (used as a number)
print $text . "!", "\n"; # 42! (used as a string)my $cups = 3;
print "I want $cups cups\n"; # I want 3 cups
print 'I want $cups cups', "\n"; # I want $cups cupsuse constant MAX_LIVES => 3;
print "Lives: ", MAX_LIVES, "\n";Rowan | level 7 | 42.5 HP | mage: yesStart: 20
After deposit: 35
Doubled: 70
After snack: 62