Code References

Similar to array- or hashrefs, you can have a pointer to a code block: a coderef. The syntax is slightly different than references to hashes or arrays:


Coderefs are most typically used in "closures" or "anonymous subs": subroutines that are not named. This is best illustrated by an example:

 # Expects one argument and one coderef. Runs the coderef on the
 # argument and prints out whatever the coderef returns.
 sub process {
    my ($arg, $code) = @_;
    print("Result after running the code: ", &$code($arg), "\n");

 # Invocation to show the upperased version of the argument,
 # see 'perldoc -f uc' to see what uc(..) does
 process('Hello World', sub {
            my $arg = shift;
            return "Uppercased string is: " . uc($arg);

 # Invocation to show the length of the argument,
 # see 'perldoc -f length' to see what length(..) does
 process('Hello World', sub {
            my $arg = shift;
            return "String length: " . length($arg) . " characters";