Here's a complete, working script that demonstrates what you're asking.
sub a { print "Hello World!\n"; }
sub b {
my $func = $_[0];
$func->();
}
b(\&a);
Here's an explanation: you take a reference to function a
by saying \&a
. At that point you have a function reference; while normally a function would be called by saying func()
you call a function reference by saying $func->()
The ->
syntax deal with other references as well. For example, here's an example of dealing with array and hash references:
sub f {
my ($aref, $href) = @_;
print "Here's an array reference: $aref->[0]\n"; # prints 5
print "Here's a hash ref: $href->{hello}\n"; # prints "world"
}
my @a = (5, 6, 7);
my %h = (hello=>"world", goodbye=>"girl");
f(\@a, \%h);