← Back to Perl Course | Chapter 2: Variables | Lesson 7 of 7

Lists

A list is a comma-separated group of values, and Perl can assign, swap and unpack them in one step.

In this page:

  1. Lists

Lists

A list is not the same thing as an array: an array is a variable, while a list is a temporary sequence of values. You can assign a list to several variables at once, swap two variables with a list assignment, and build ranges with 1..5. Lists that are put inside other lists get flattened into one long list.

Note: In a list assignment, extra values are dropped and missing values become undef.

Example: Lists

perl
use strict;
use warnings;

my ($x, $y, $z) = (10, 20);
print "z is ", defined $z ? "defined" : "undef", "\n";
($x, $y) = ($y, $x);
print "swapped: x=$x y=$y\n";
my @small = (1, 2);
my @big = (0, @small, 3, (4, 5));
print "flattened: @big\n";
my @range = (1 .. 5);
print "range: @range\n";
my @letters = ('a' .. 'e');
print "letters: @letters\n";
my ($head, @rest) = @big;
print "head=$head rest=@rest\n";
print "backward range: ", scalar(() = (5 .. 1)), " elements\n";

# Output:
# z is undef
# swapped: x=20 y=10
# flattened: 0 1 2 3 4 5
# range: 1 2 3 4 5
# letters: a b c d e
# head=0 rest=1 2 3 4 5
# backward range: 0 elements
Common Mistakes
  1. Expecting nested lists to stay nested when placing arrays inside a list
  2. Using a range such as 5..1 and expecting a countdown
  3. Forgetting that a comma list in scalar context returns the last element
Chapter Summary
  • A list is a temporary sequence of values
  • List assignment unpacks values into variables
  • Lists flatten when combined
  • 1..5 builds a range
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.