Anonymous subroutines in Perl are unnamed functions that can be created on the fly and assigned to variables or passed as arguments to other functions. They provide a flexible way to create and use functions without explicitly defining them with names.
To create an anonymous subroutine in Perl, use the sub
keyword followed by a code block. Here's the basic syntax:
my $subroutine = sub {
# Code block
};
Anonymous subroutines can be invoked using the reference stored in the variable:
$subroutine->(); # Invoke the subroutine
my $greet = sub {
my $name = shift;
print "Hello, $name!\n";
};
$greet->("Alice"); # Output: Hello, Alice!
sub process_data {
my ($data, $callback) = @_;
$callback->($data);
}
my $double = sub {
my $value = shift;
return $value * 2;
};
my $result = process_data(5, $double);
print "Result: $result\n"; # Output: Result: 10
To deepen your understanding of Perl subroutines, explore these related topics:
By mastering anonymous subroutines, you'll enhance your ability to write flexible and efficient Perl code, opening up new possibilities for functional programming and callback-based designs.