data-structures intermediate

How to slice an array in Perl?

Question

How to slice an array in Perl?

In Perl, array slicing is a way to extract multiple elements from an array by specifying a list of indices inside square brackets with the array's @ sigil. This is different from accessing a single element, which uses the scalar $ sigil.

How Array Slices Work

You use the @ sigil combined with brackets containing a list of indices or ranges to get a list of elements:


@slice = @array[0, 2, 4];

This returns the elements at positions 0, 2, and 4 from @array. The key is using @ on the left to indicate list context — $array[1,2] is invalid because the comma is interpreted in scalar context, returning only a single element.

Runnable Example

Here is a complete, runnable example demonstrating basic array slicing and printing the results:


use strict;
use warnings;

my @fruits = qw(apple banana cherry date elderberry fig grape);

# Slice to get elements at positions 1, 3, and 5
my @selected = @fruits[1, 3, 5];
print "Selected fruits: ", join(", ", @selected), "\n";

# Using a range slice from index 2 to 4
my @middle = @fruits[2 .. 4];
print "Middle fruits: ", join(", ", @middle), "\n";

This script outputs:


Selected fruits: banana, date, fig
Middle fruits: cherry, date, elderberry

Important Points About Array Slices in Perl

  • Sigil matters: Use @array[ ... ] for slices (list context).
  • Supports ranges and lists: You can slice with explicit indices or ranges (e.g., 2 .. 4).
  • Negative indices: Allowed for slicing, e.g. @array[-1] for last element.
  • Assignment works: You can assign to slices, such as @array[0,2] = ('x','y').
  • Out-of-bounds: Returns undef silently.

Common Pitfalls

  • Using scalar sigil $ with a list of indices (e.g., $array[1,3]) returns a single element, usually the last index.
  • Confusing list context with scalar context—slices require the @ sigil to return lists.

Summary

Array slicing leverages Perl's flexible sigil and context system (reflecting the "There's More Than One Way To Do It" philosophy). Use @array[ ... ] with a list or range of indices to extract multiple elements efficiently and clearly.

Verified Code

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

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

Was this helpful?

Related Questions