Perl
array permutations
programming
algorithms
code examples

How can I generate all permutations of an array in Perl?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

To generate all permutations of an array in Perl, you can either use a module such as Algorithm::Permute or write a small recursive function yourself. The right choice depends on whether you want the shortest working solution or a version you fully control and understand.

Use a Module for the Simplest Approach

Algorithm::Permute is a common option because it handles the permutation logic for you:

perl
1use strict;
2use warnings;
3use Algorithm::Permute;
4
5my @items = qw(a b c);
6my $perm = Algorithm::Permute->new(\@items);
7
8while (my @p = $perm->next) {
9    print join(",", @p), "\n";
10}

This is concise and easy to read. If the job is simply "iterate through every ordering," a module is often the cleanest answer.

Write a Recursive Version When You Want Full Control

You can also generate permutations directly:

perl
1use strict;
2use warnings;
3
4sub permute {
5    my ($items, $start) = @_;
6    $start //= 0;
7
8    if ($start == $#$items) {
9        print join(",", @$items), "\n";
10        return;
11    }
12
13    for my $i ($start .. $#$items) {
14        @$items[$start, $i] = @$items[$i, $start];
15        permute($items, $start + 1);
16        @$items[$start, $i] = @$items[$i, $start];
17    }
18}
19
20my @items = qw(a b c);
21permute(\@items);

This works by swapping the current position with each later position, recursing, and then swapping back. It is a useful pattern because it avoids allocating a completely new array at every step.

Understand the Cost

Permutation counts grow factorially. An array of length 3 has 6 permutations, length 4 has 24, length 5 has 120, and so on. That growth becomes impractical quickly.

So the real question is often not "how do I generate permutations?" but "can I afford to generate all of them?" For arrays of any meaningful size, the answer may be no.

Return Results Instead of Printing Them

If you need the permutations as data, collect them instead of printing:

perl
1use strict;
2use warnings;
3
4sub all_permutations {
5    my ($items, $start, $out) = @_;
6    $start //= 0;
7    $out   //= [];
8
9    if ($start == $#$items) {
10        push @$out, [@$items];
11        return $out;
12    }
13
14    for my $i ($start .. $#$items) {
15        @$items[$start, $i] = @$items[$i, $start];
16        all_permutations($items, $start + 1, $out);
17        @$items[$start, $i] = @$items[$i, $start];
18    }
19
20    return $out;
21}
22
23my $result = all_permutations([qw(a b c)]);
24print scalar(@$result), "\n";

Be careful with this version on larger arrays because storing every permutation can consume a lot of memory.

Choose the Right Style

Use a module when the goal is clarity and quick delivery. Use the recursive version when you need custom behavior, educational value, or tighter control over how the permutations are consumed.

In both cases, try to stream results instead of storing them all unless you truly need the whole set in memory.

Common Pitfalls

  • Forgetting how fast factorial growth explodes. Generating every permutation of a large array becomes impractical very quickly.
  • Storing all permutations in memory when simple streaming output would be enough.
  • Mutating the original array without swapping elements back after recursion.
  • Reimplementing a complex algorithm when a well-known module would be simpler and safer.
  • Assuming duplicate input values will produce only unique permutations automatically. Extra logic is needed if uniqueness matters.

Summary

  • In Perl, a module such as Algorithm::Permute is the quickest route to all permutations.
  • A recursive swap-based function is a solid manual implementation.
  • Permutations grow factorially, so input size matters a lot.
  • Stream results when possible instead of storing every permutation.
  • Choose between module convenience and custom control based on the actual use case.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.