http://qs1969.pair.com?node_id=11147042

ibm1620 has asked for the wisdom of the Perl Monks concerning the following question:

When I write a recursive subroutine, I usually have to write two subroutines: A(), which sets things up properly and then calls B(), which is the actual recursive subroutine and is not intended to be called by anyone except itself and A().

I wrote a simple routine make_backup($file) to make a backup of a file by copying it to $file.bak, first renaming any previous backups by appending another ".bak". In doing so I accidentally located the recursive subroutine inside the first subroutine (which I didn't know was possible).

use v5.36; use File::Copy; # Copy $path to $path.bak, preserving all earlier backups sub make_backup ($path ) { my $path_bak; if (-e $path) { $path_bak = _preserve_previous_backup($path); copy $path_bak, $path; } return $path_bak; # undef if path didn't exist sub _preserve_previous_backup ( $path ) { my $path_bak = "${path}.bak"; if (-e $path_bak) { _preserve_previous_backup($path_bak ); } move $path, $path_bak; return $path_bak; } }
And it worked. I thought this was a nifty way to encapsulate the "non-public" subroutine, until I realized what I'd done was to create a closure, which I'm unfamiliar with at this point.

I do like the idea of nesting the recursive piece inside the outer sub in this manner, and it does appear to work properly, but from what I've learned so far, this is not what "closures" are meant for. Could I get some enlightened commentary on the most-likely-unwise thing I'm doing?