Free preview.You're sampling one lesson — enroll free to unlock all 10 lessons and track your progress.
Enroll free
lesson

Closures and Higher-Order Functions

Closures and Higher-Order Functions

In this lesson — part of Advanced Features — you'll learn closures and higher-order functions in Perl and why it matters in real work.

Why it matters

Functions that take or return functions unlock concise, composable code.

Key ideas

  • Functions as values
  • map / filter / reduce
  • Callbacks
  • Composition

In practice

Here's how it looks in idiomatic Perl:

use strict; use warnings;
# Subs are first-class: pass and return code refs
sub apply_twice { my ($f, $x) = @_; return $f->($f->($x)) }
my $inc = sub { $_[0] + 1 };
print apply_twice($inc, 5), "\n";        # 7
sub multiplier { my $n = shift; return sub { $_[0] * $n } }
my $triple = multiplier(3);
print $triple->(10), "\n";               # 30
my @r = map { $_->(4) } ($inc, $triple);
print "@r\n";

Perl note: Anonymous subs (sub { ... }) are code references — first-class values you store, pass, and return — and you invoke them with the arrow $f->(...) rather than bare $f(...).

Try it yourself

Exercise: In Perl, use map and filter to get the squares of the even numbers.

Recap

You now understand closures and higher-order functions and can apply it in Perl. Mark this lesson complete and continue to the next one.