PERL / CHAPTER 02

Arrays, hashes, and context

Intermediate

Read list and scalar contexts without confusing absence with false values.

By the end of this chapter

  • Index arrays and hash elements
  • Use scalar array context for length
  • Distinguish exists from defined

The idea

Enter with scalar variables understood. An array stores an ordered sequence, while a hash associates string keys with scalar values. The sigil follows the accessed value: @items names the array, but $items[0] accesses one scalar element. Similarly, %counts names a hash and $counts{word} accesses one value. Keep the collection name and the element’s scalar role separate.

Context determines what an expression supplies. An array in scalar context gives its element count, while list context supplies its elements. For hashes, exists asks whether a key is present and defined asks whether its stored value is not undef. These questions differ from truthiness: a stored zero is defined even though it is false in a boolean test. Choose the check that matches the information being requested.

Perl example
use strict; use warnings;
my @items=(4,7,9);
my %values=(score=>0);
print scalar(@items), " ", (exists $values{score} ? 1 : 0), " ", (defined $values{score} ? 1 : 0), "\n";
Result
3 1 1

The array contains three elements. The score key exists and holds a defined zero rather than an undefined value.

Try it yourself

Construct a hash with one undef value and compare exists with defined for that key.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What does scalar(@items) return for an array?