WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Perl · Intermediate · question 37 of 100

How can you create and use anonymous functions (closures) in Perl?

📕 Buy this interview preparation book: 100 Perl questions & answers — PDF + EPUB for $5

Anonymous functions (or closures) are functions that are not named and can be used as values, passed to other functions, and used to create higher-order functions. They are created using the ‘sub‘ keyword followed by a block of code, just like a regular named function. However, they are not associated with a name, and the keyword ‘sub‘ is followed by a set of parentheses containing any arguments the function should receive.

Here is an example of an anonymous function that takes two arguments and returns their sum:

my $sum = sub ($x, $y) { $x + $y };

In this example, the anonymous function is assigned to a scalar variable ‘$sum‘. This variable can be treated like any other scalar, and passed as an argument to other functions.

You can call the anonymous function by enclosing its arguments in parentheses and dereferencing it using an arrow ‘->‘:

my $result = $sum->(2, 3); # $result equals 5

Here, the anonymous function ‘$sum‘ is called with arguments 2 and 3, and the result is assigned to the variable ‘$result‘.

Anonymous functions are commonly used with higher-order functions, which are functions that take other functions as arguments or return functions as results. Here is an example of a higher-order function that takes an anonymous function and returns a new anonymous function that multiplies its argument by a constant:

sub make_multiplier {
  my $factor = shift;
  return sub ($n) { $factor * $n };
}

my $double = make_multiplier(2);

my $result = $double->(5); # $result equals 10

In this example, the ‘make_multiplier‘ function returns a new anonymous function that multiplies its argument by the constant ‘$factor‘. The ‘$factor‘ variable is initialized using the ‘shift‘ function, which takes the first argument to ‘make_multiplier‘.

The ‘$double‘ variable is initialized with the result of calling ‘make_multiplier‘ with an argument of 2. This creates a new anonymous function that multiplies its argument by 2, and assigns it to ‘$double‘.

Finally, ‘$double‘ is called with an argument of 5, resulting in the value 10. This shows how anonymous functions can be used to create higher-order functions that can be used to simplify complex code.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Perl interview — then scores it.
📞 Practice Perl — free 15 min
📕 Buy this interview preparation book: 100 Perl questions & answers — PDF + EPUB for $5

All 100 Perl questions · All topics