Three shapes of data
Most programs juggle three shapes of data. A single value: a name, a price, a count. An ordered list of values: the lines of a file, the steps of a recipe. And a lookup table from keys to values: words to their counts, usernames to email addresses, countries to capitals.
Many languages give you one way to name a variable and then many types of value to put in it. Perl does something different: it has three kinds of variable, one for each shape, and it marks each with a symbol at the front of the name called a sigil.
| Sigil | Kind | Holds | Example |
|---|---|---|---|
$ | scalar | one value: a number, a string, a reference, or undef | $price |
@ | array | an ordered list of scalars, indexed from 0 | @lines |
% | hash | an unordered set of key/value pairs; keys are strings | %capital |
The sigil is not decoration. It tells you, at a glance, how many things an expression produces, and it tells Perl too. That leads to Perl's most distinctive idea, context: the same expression can mean different things depending on whether the code around it wants one value or a list. Once context clicks, a great deal of Perl that looked like magic becomes obvious.
Scalars: numbers, strings and undef
Definition— Scalar
A scalar variable, written with $, holds exactly one value. That value can be a number (stored as an integer or a floating-point number), a string of any length, a reference (lesson 4), or the special value undef, which means "no value". Perl converts between numbers and strings automatically whenever an operator needs the other one.
Because a scalar can be either a number or a string, the operator decides how to treat it. That is why Perl has two families of operators where most languages have one:
| Meaning | Numbers | Strings |
|---|---|---|
| equal, not equal | ==, != | eq, ne |
| less than, greater than | <, >, <=, >= | lt, gt, le, ge |
| three-way compare (−1, 0 or 1) | <=> | cmp |
| combine | +, -, *, /, **, % | . (join), x (repeat) |
Here they are at work, together with the question every language must answer: which values count as false?
use strict;
use warnings;
use feature qw(say);
my $population = 1_400_000; # underscores are just for readability
my $ratio = 7 / 2; # division is never truncated
my $hex = 0xFF;
say "$population $ratio $hex ", 2 ** 10, " ", 17 % 5;
# The operator decides: numbers or strings?
say "10.0" == 10 ? "== says equal" : "== says different";
say "10.0" eq 10 ? "eq says equal" : "eq says different";
say "9" < "10" ? "< : 9 before 10" : "< : 10 before 9";
say "9" lt "10" ? "lt: 9 before 10" : "lt: 10 before 9";
say "-" x 12; # x repeats a string
say "Ha" x 3, "!";
my $id = "az9";
$id++; # magic string increment
say "next id: $id";
# What counts as false?
for my $value (0, 1, "", "0", "0.0", "00", " ", "abc", undef) {
my $shown = defined $value ? "'$value'" : 'undef';
printf "%-6s is %s\n", $shown, $value ? "true" : "false";
}
my $nickname;
say "Hello, ", $nickname // "friend"; # defined-or: a default for undefIt printed:
1400000 3.5 255 1024 2
== says equal
eq says different
< : 9 before 10
lt: 10 before 9
------------
HaHaHa!
next id: ba0
'0' is false
'1' is true
'' is false
'0' is false
'0.0' is true
'00' is true
' ' is true
'abc' is true
undef is false
Hello, friendA few things deserve a second look.
"10.0" == 10is true, because as numbers both are ten."10.0" eq 10is false, because as strings"10.0"and"10"differ. Choosing==oreqis choosing what "equal" means."9" lt "10"is false: in dictionary order,"1"comes before"9", so"10"sorts first. This is the same reason file listings putfile10beforefile9.7 / 2is3.5. Perl's/never throws away the fraction; useint(7 / 2)when you want 3.++on a string that looks like letters followed by digits increments it like an odometer:az9becomesba0. This is occasionally handy for generating labels and occasionally a surprise.//is the defined-or operator (Perl 5.10): it gives its left side unless that is undef. Unlike||, it keeps a legitimate0or empty string.
Definition— Truth in Perl
Exactly four kinds of scalar are false: the number 0, the string "0", the empty string "", and undef. Everything else is true, including "0.0", "00", " " and the string "false". Perl decides by looking at the value as a string: if it is empty or exactly "0", it is false.
Strings can be written with single quotes (literal) or double quotes (interpolating). For long text, a here-document reads until a terminating word; the ~ form (Perl 5.26) strips the common indentation:
my $city = 'Accra';
print <<~END;
Dear $city office,
the report is attached.
ENDArrays: ordered lists
An array, written with @, holds an ordered list of scalars. You can grow and shrink it from either end, index it from the front (0, 1, 2, …) or from the back (−1 is the last), and take slices of several elements at once.
use strict;
use warnings;
use feature qw(say);
my @rivers = ('Nile', 'Amazon', 'Yangtze');
push @rivers, 'Mekong', 'Danube'; # add to the end
unshift @rivers, 'Volga'; # add to the front
say "All: @rivers"; # arrays interpolate with spaces
say "First: $rivers[0], last: $rivers[-1]";
say "Count: ", scalar(@rivers), ", last index: $#rivers";
my $gone = pop @rivers; # remove from the end
my $also = shift @rivers; # remove from the front
say "Removed $gone and $also";
my @middle = @rivers[1 .. 2]; # a slice: several elements at once
say "Slice: @middle";
splice @rivers, 1, 1, 'Congo', 'Niger'; # replace 1 element with 2
say "After splice: ", join(", ", @rivers);
my @sorted = sort @rivers; # string order by default
my @lengths = map { length } @rivers; # transform each element
my @long = grep { length > 5 } @rivers; # keep some elements
say "Sorted: @sorted";
say "Lengths: @lengths";
say "Long: @long";
my @numbers = (10, 9, 100, 2);
my @wrong = sort @numbers;
my @right = sort { $a <=> $b } @numbers;
say "Default sort: @wrong";
say "Numeric sort: @right";It printed:
All: Volga Nile Amazon Yangtze Mekong Danube
First: Volga, last: Danube
Count: 6, last index: 5
Removed Danube and Volga
Slice: Amazon Yangtze
After splice: Nile, Congo, Niger, Yangtze, Mekong
Sorted: Congo Mekong Niger Nile Yangtze
Lengths: 4 5 5 7 6
Long: Yangtze Mekong
Default sort: 10 100 2 9
Numeric sort: 2 9 10 100The sigil shows what you get
The line that surprises everyone is $rivers[0]. Why $ and not @? Because the sigil describes the result, not the variable. One element of an array is one scalar, so it is written with $. A slice, @rivers[1 .. 2], gives several elements, a list, so it is written with @. The variable's name is rivers and the brackets say it is the array; the sigil says "one" or "many".
Once you read sigils that way, the rest follows: $#rivers is the last index (a single number), and scalar(@rivers) is the length.
map, grep and sort
These three take a block and a list and give back a list. Inside the block, the special variable $_ is each element in turn.
map { BLOCK } LISTtransforms: one output (or several, or none) per input.grep { BLOCK } LISTfilters: keeps the elements for which the block is true.sort { BLOCK } LISTorders, comparing two elements called$aand$b. The block must return a negative number, zero or a positive number, which is exactly what<=>andcmpproduce.{ $a <=> $b }is ascending numeric,{ $b <=> $a }descending,{ $a cmp $b }the default string order.
Many built-ins, such as length, uc and lc, use $_ when given no argument. That is why map { length } @rivers works.
Misconception
"sort sorts numbers." Without a block, sort compares as strings, so (10, 9, 100, 2) becomes 10 100 2 9. Always write sort { $a <=> $b } for numbers. This is one of the most common bugs in Perl code written by newcomers, and it hides well because small test data often happens to sort correctly either way.
Hashes: lookup tables
A hash, written with %, maps string keys to scalar values. Other languages call this a dictionary, a map or an associative array; Perl's name comes from the hash table that implements it. Lookups, insertions and deletions take constant time on average, whatever the size.
use strict;
use warnings;
use feature qw(say);
my %capital = (
Kenya => 'Nairobi',
Peru => 'Lima',
Vietnam => 'Hanoi',
);
$capital{Norway} = 'Oslo'; # add a pair
say "The capital of Peru is $capital{Peru}.";
for my $country (sort keys %capital) { # keys come in no fixed order
say " $country: $capital{$country}";
}
say exists $capital{Chile} ? "Chile known" : "Chile not known";
delete $capital{Vietnam};
say "Now ", scalar(keys %capital), " countries";
my @cities = @capital{qw(Kenya Norway)}; # a hash slice
say "Two capitals: @cities";
# Counting is the classic use of a hash.
my %seen;
my @votes = qw(tea coffee tea mate tea coffee);
$seen{$_}++ for @votes;
for my $drink (sort { $seen{$b} <=> $seen{$a} or $a cmp $b } keys %seen) {
say "$drink: $seen{$drink}";
}It printed:
The capital of Peru is Lima.
Kenya: Nairobi
Norway: Oslo
Peru: Lima
Vietnam: Hanoi
Chile not known
Now 3 countries
Two capitals: Nairobi Oslo
tea: 3
coffee: 2
mate: 1The same sigil rule applies: one value from a hash is a scalar, so it is $capital{Peru} with curly braces; several values, a slice, are @capital{...}. The fat comma => is just a comma that also quotes the word on its left, which is why Kenya => 'Nairobi' needs no quotes around Kenya. Inside {...}, a simple word key is quoted automatically too.
Some details matter in practice:
- Order. A hash has no order, and Perl deliberately randomises it between runs so that programs cannot come to depend on it (this also defends against attacks that feed a server keys chosen to collide). Whenever output order matters, iterate over
sort keys %hash. existsversusdefined.exists $h{k}asks whether the key is present;defined $h{k}asks whether its value is not undef. A key can exist with an undef value.- Counting.
$seen{$_}++ for @votesis the idiom for counting things: a missing key acts as 0, and++creates it. The statement-modifier formEXPR for LISTis the next lesson's topic. - Sorting by two keys.
$seen{$b} <=> $seen{$a} or $a cmp $bsorts by count, largest first, and breaks ties alphabetically: if the counts are equal,<=>gives 0, which is false, soorfalls through to the second comparison.
Context: one expression, two meanings
Every Perl expression is evaluated in a context, decided by what is around it. In list context, the surroundings want a list of values; in scalar context, they want exactly one. An expression can notice which one it is in and behave accordingly. That is the whole idea, and it explains a lot.
Analogy, not a formal construction
Ask a librarian "the books on Lisbon?" and the answer depends on how you asked. If you are holding out a trolley, you get the books. If you are filling in a form with one box marked "how many?", you get a number. Perl's arrays behave like that librarian: in a place that wants many things, an array gives its elements; in a place that wants one thing, it gives its size.
use strict;
use warnings;
use feature qw(say);
my @langs = qw(Perl Lua Ruby Python);
my $count = @langs; # an array in scalar context: its length
my ($first) = @langs; # list assignment: the first element
say "count=$count first=$first";
my @copy = (@langs, 'Raku'); # arrays flatten into lists
say "copy has ", scalar(@copy), " elements";
my $backwards = reverse 'stressed'; # scalar context: reverse a string
my @reversed = reverse @langs; # list context: reverse a list
say "$backwards / @reversed";
my %age = (Ana => 31, Bo => 27);
my @flat = %age; # a hash in list context: key, value, ...
say "flat list has ", scalar(@flat), " items";
say "Interpolated: @langs"; # a list, joined with spaces
say "Concatenated: " . @langs . " items"; # the dot wants a scalar
my @empty = ();
say "empty array in boolean context is ", (@empty ? "true" : "false");It printed:
count=4 first=Perl
copy has 5 elements
desserts / Python Ruby Lua Perl
flat list has 4 items
Interpolated: Perl Lua Ruby Python
Concatenated: 4 items
empty array in boolean context is falseHow to tell which context you are in:
- Assignment to a scalar (
my $count = ...) gives scalar context. Assignment to an array, a hash or a list in parentheses (my ($first) = ...) gives list context. The parentheses inmy ($first)are the whole difference between "how many" and "the first one". - Operators that want one value, such as
.,+,==and the condition ofifor?:, give scalar context. An empty array is therefore false and a non-empty one true, which is whyif (@errors)is idiomatic. - Function arguments and the inside of
( ... )lists are list context. Arrays and hashes flatten there:(@langs, 'Raku')is a list of five scalars, not a list containing an array. scalar(EXPR)forces scalar context when you need it, as insay "Count: ", scalar(@rivers).
Built-in functions document their behaviour in each context. reverse reverses a list in list context and reverses the characters of a string in scalar context. localtime returns nine numbers in list context and a readable date string in scalar context. keys %h in scalar context is the number of keys. When you write your own subroutines, the next lesson shows how they can do the same.
Misconception
"my $n = (4, 5, 6); sets $n to 3, the length of the list." It does not: it sets $n to 6, and use warnings complains about the "useless" 4 and 5. A literal list in scalar context is the comma operator, which evaluates each item and keeps the last. Only an array in scalar context gives its length. If you want the length, put the values in an array first, or write my $n = () = (4, 5, 6);, an idiom you will meet again with regular expressions.
Flattening, and what it means for real programs
Flattening is convenient: push @all, @more appends every element of @more, and my %merged = (%defaults, %options) merges two hashes, with later keys winning. But it also sets a limit. Because (@a, @b) is just one long list, you cannot store an array inside another array or a hash this way. An attempt like my %team = (players => @names) produces a hash whose pairs are players => $names[0], $names[1] => $names[2], and so on: almost certainly not what you meant.
The way out is the reference, a scalar that points to an array or hash. With references you can build lists of hashes, hashes of lists and any nesting you like, and they are the subject of lesson 4. For now, keep the rule in mind: arrays and hashes hold scalars, and lists flatten.
A few more habits from working Perl programmers:
- Name arrays in the plural (
@files) and hashes for what they map (%size_of,%capital) so that$size_of{$file}reads like English. - Reach for the core module List::Util before writing loops:
sum,max,min,first,any,allanduniqare all there (use List::Util qw(sum max);). - Use
existsto test for membership, and a hash as a set:my %allowed = map { $_ => 1 } @names;thenif ($allowed{$user}). - When debugging, print a structure with the core module Data::Dumper; lesson 4 shows it.
Exercises
1. Scalars, arrays and hashes
Warm-upComputationalWhat does this program print?
use strict;
use warnings;
use feature qw(say);
my @scores = (3, 1, 20, 100);
my @sorted = sort @scores;
say "@sorted";
2. Scalars, arrays and hashes
Warm-upComputationalWhat number does this program print?
use strict;
use warnings;
use feature qw(say);
my @letters = qw(a b c d e);
my $n = @letters;
say $n + $#letters;
3. Scalars, arrays and hashes
CoreComputationalThis program prints some fruit names, one per line. Which ones?
use strict;
use warnings;
use feature qw(say);
my %stock = (apple => 3, pear => 0, plum => 7, fig => undef);
delete $stock{plum};
my @known = grep { defined $stock{$_} } keys %stock;
say for sort @known;
4. Scalars, arrays and hashes
CoreComputationalWhat does this program print?
use strict;
use warnings;
use feature qw(say);
my @words = qw(sun moon star);
my ($first) = @words;
my $size = @words;
say "$first$size";
5. Scalars, arrays and hashes
StretchComputationalWhat does this program print?
use strict;
use warnings;
use feature qw(say);
my $s = reverse "hello";
my @r = reverse "hello";
say "$s @r";
6. Scalars, arrays and hashes
CoreComputationalWhat does this program print?
use strict;
use warnings;
use feature qw(say);
my @nums = (4, 8, 15, 16, 23, 42);
my @picked = map { $_ * 10 } grep { $_ % 2 } @nums;
say join ",", @picked;
7. Scalars, arrays and hashes
CoreHumanWhich of these values are false in Perl? Choose all that apply.
8. Scalars, arrays and hashes
Warm-upHumanYou want to check whether the user typed exactly yes. Which test is right?
Further reading and resources
- perldataThe official reference for scalars, arrays, hashes, literals, slices and context.
- perlopEvery operator with its precedence, including the numeric and string comparison families.
- perlfuncAll built-in functions, grouped by kind, with notes on how each behaves in scalar and list context.
- List::UtilThe core module with sum, max, min, first, any, all, uniq, shuffle and more.