Scalars and Variables
A scalar, written with a $ sigil, holds exactly one value — a string, a number, or a reference (covered later in this course). Perl doesn't force you to pick which kind up front the way a statically typed language would; the same scalar can hold a number in one line and a string in the next, and Perl converts between them as operators demand.
`my` declares a new variable scoped to the enclosing block — not the whole file, not a function's entire remaining body, but specifically the nearest set of curly braces (or the rest of the file, if there are none). This is called lexical scoping.
use strict; use warnings; my $name = "Ada"; my $age = 36; my $pi = 3.14159; print "Name: $name\n"; print "Age: $age\n"; print "Pi: $pi\n";
Name: Ada Age: 36 Pi: 3.14159
A `my` declared inside a block shadows an outer variable of the same name only within that block — the outer one is untouched once the block ends:
use strict;
use warnings;
my $x = 10;
{
my $x = 20;
print "Inner x: $x\n";
}
print "Outer x: $x\n";
Inner x: 20 Outer x: 10
Perl also has `our` (a lexically scoped alias to a package-global variable) and `local` (temporarily overrides a global's value for the current dynamic scope) — both far less common than `my` in everyday code, and not needed for anything in this course. Next: strings — interpolation, concatenation, and common string functions.
Practice exercise
Declare my $a = 6 and my $b = 7, then print their product using print $a * $b.