Subroutines can be nested. In other words, you may define a sub inside another sub. Let's see it in the next example, which lists the present tense forms of regular English verbs:
sub list_verb_forms($verb) {
sub make_form($base, $pronoun) {
my $form = $base;
# Adds the 's' ending for he, she, and it.
# The check uses a regular expression.
# We cover regular expressions in Chapter 11, Regexes.
$form ~= 's' if $pronoun ~~ /^ [ he | she | it ] $/;
return "$pronoun $form";
}
my @pronouns = <I we you he she it they>;
for @pronouns -> $pronoun {
say make_form($verb, $pronoun);
}
}
list_verb_forms('read');
The result of this program is exactly what we wanted, as you can see here:
I read we read you read he reads she reads it reads they...