ibm1620 has asked for the wisdom of the Perl Monks concerning the following question:
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?
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Recursive subroutines and closures
by haukex (Archbishop) on Sep 21, 2022 at 06:28 UTC | |
Re: Recursive subroutines and closures (updated)
by AnomalousMonk (Archbishop) on Sep 21, 2022 at 05:41 UTC | |
by ibm1620 (Hermit) on Sep 22, 2022 at 02:29 UTC | |
Re: Recursive subroutines and closures
by GrandFather (Saint) on Sep 21, 2022 at 01:50 UTC | |
by ibm1620 (Hermit) on Sep 22, 2022 at 02:36 UTC | |
Re: Recursive subroutines and closures
by jwkrahn (Abbot) on Sep 21, 2022 at 03:53 UTC | |
Re: Recursive subroutines and closures
by madtoperl (Hermit) on Sep 21, 2022 at 13:47 UTC |