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).
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.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; } }
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?
In reply to Recursive subroutines and closures by ibm1620
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |