Note because _preserve_previous_backup doesn't actually use ("close over") any of the variables from make_backup, you haven't really created a closure - instead, this actually has the potential for accidentally using variables from the outer sub, which can lead to issues like the ones GrandFather showed. To add to what jwkrahn noted, in this case you can just as well place _preserve_previous_backup in the main body of your code, the leading underscore already indicates that this is not a part of the public API and one should only call it when one knows what one is doing. And while the lexical subroutines noted by AnomalousMonk are indeed a thing (as of Perl 5.18), personally I actually use anonymous subs for this kind of thing. Just for example, consider this pseudocode:
sub process_files ($ext, @files) {
# let's say we split @files in two sets
my @foo_files = ...;
my @bar_files = ...;
# but part of the processing is the same
my $new_name = sub ($name, $some_param) {
... # some longer/complex code to munge the filename
# note how this uses at least one var from the outer scope
return $new_filename . $ext;
};
# different processing for the two sets
for my $file (@foo_files) {
my $fn = $new_name->($file, "foo");
...
}
for my $file (@bar_files) {
my $fn = $new_name->($file, "bar");
...
}
}
If an anonymous sub needs to call itself recursively, one backwards-compatible way to define it is my $code; $code = sub { ... $code->() ... };, or, as of Perl 5.16, there is the __SUB__ function. Anonymous subs can also be used in a module if one really wants to hide the code from access outside the module; like other lexical variables, my $private_func = sub { ... }; in a module won't be accessible from the outside, though my personal opinion is that this is a bit overkill, and prefixing the sub name with an underscore should be enough - part of the Perl philosophy of "It would prefer that you stayed out of its living room because you weren't invited, not because it has a shotgun."