1 | One can predeclare subroutines with |
2 | sub name; # may be used before implementation appears |
3 | Subroutines may be defined anonymously: |
4 | sub newprint { |
5 | my $x = shift; |
6 | # return anonymous subroutine: |
7 | return { my $y=shift; print "$x $y!\n"; }; |
8 | } |
9 | $h = newprint("Howdy"); # store anonymous subroutine |
10 | &$h("World"); # call anonymous subroutine, which prints |
11 | "Howdy World!" |
12 | Note the $x in anonymous subroutine is private and retains value "Howdy" in $h even when newprint is called again: |
13 | $g = newprint("Hello"); # $g has separate instance of $x |