variables beginner

How to create an array in Perl and access its elements?

Question

How to create an array in Perl and access its elements?

In Perl, arrays are ordered lists of scalar values (strings, numbers, etc.) that allow you to store multiple related items in a single variable. Working with arrays is fundamental to Perl programming, and understanding how to create and access them is an essential skill for beginners.

Creating an Array

You create an array by assigning a list of values to a variable with an @ sigil. For example:


my @fruits = ('apple', 'orange', 'banana');

Here, @fruits is an array containing three elements: 'apple', 'orange', and 'banana'. Unlike scalar variables that use $, arrays use @ to indicate they hold multiple values.

Accessing Array Elements

You access individual elements of an array by using the $ sigil (because each element is a scalar) plus the array name and the index in square brackets:


my $first_fruit = $fruits[0];
my $second_fruit = $fruits[1];

Array indices in Perl start from zero, so $fruits[0] is the first element ('apple'), $fruits[1] is the second, and so on.

Key Points About Perl Arrays

  • Sigils matter: @array refers to the entire array (list context), while $array[index] refers to one scalar element.
  • Flexible size: Arrays grow automatically when you assign to an index beyond the current size.
  • Context: When you want multiple elements (a slice), you use @array[@indices] to get a list back.
  • TMTOWTDI: Perl's "There's more than one way to do it" philosophy means you can create and access arrays in a variety of ways, such as splitting strings or pushing/popping elements.

Example: Create, Access, and Print Array Elements


use strict;
use warnings;

# Create an array of colors
my @colors = ('red', 'green', 'blue');

# Access individual elements
my $first_color = $colors[0];
my $second_color = $colors[1];

# Print the entire array
print "All colors: @colors\n";

# Print individual elements
print "First color: $first_color\n";
print "Second color: $second_color\n";

# Change an element
$colors[2] = 'yellow';
print "After change, third color: $colors[2]\n";

# Access out of bounds returns undef
my $fourth_color = $colors[3];
if (defined $fourth_color) {
    print "Fourth color: $fourth_color\n";
} else {
    print "Fourth color is not defined (index out of range)\n";
}

This program demonstrates:

  • Declaring an array with @colors
  • Accessing elements with indices 0 and 1
  • Printing the entire array directly
  • Modifying an element
  • Handling out-of-bounds indexes gracefully

Common Pitfalls

  • Using the wrong sigil: Remember to use @ for arrays and $ for single elements.
  • Off-by-one errors: Array indexing starts at 0, not 1.
  • Assigning via scalar to an array variable: my $var = (1,2,3) only assigns the last list element to scalar.
  • Confusing array slices and scalar element access: use @array[@indices] for slices vs $array[index] for individual elements.

Understanding arrays and their access patterns unlocks many powerful Perl programming idioms and makes your scripts efficient and clean. Experiment with creating arrays of different data and accessing them in your code!

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 8ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
(empty)
STDERR
(empty)

Was this helpful?

Related Questions