Perl: Creating a reference to a subroutine

Perl allows you to create a reference to subrouting and store it in a variable. This allows subroutines to be passed around to other functions. In Perl speak these are called coderefs. There are two ways to create them:


my $one = sub { print "Hello world!"; }
my $two = \&hello_world;

sub hello_world {
    print "Hello world!";
}

Calling a code reference is simple:

$coderef->(); # No params
$coderef->($param1, $param2);
Leave A Reply
All content licensed under the Creative Commons License