aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorCY Fung <fungcheokyin@gmail.com>2023-02-12 23:36:45 +0800
committerCY Fung <fungcheokyin@gmail.com>2023-02-12 23:36:45 +0800
commit50a972935d2848c6f69e0de87c74cffc80d422ed (patch)
treecc37c05bac09a5532fc4bea8a191d0062b78f797
parent84675e41ffaaa804f00c7f35ddbd0a7e37ea2dce (diff)
downloadperlweeklychallenge-club-50a972935d2848c6f69e0de87c74cffc80d422ed.tar.gz
perlweeklychallenge-club-50a972935d2848c6f69e0de87c74cffc80d422ed.tar.bz2
perlweeklychallenge-club-50a972935d2848c6f69e0de87c74cffc80d422ed.zip
Week 203 Task 2
-rw-r--r--challenge-203/cheok-yin-fung/perl/ch-2.pl49
1 files changed, 49 insertions, 0 deletions
diff --git a/challenge-203/cheok-yin-fung/perl/ch-2.pl b/challenge-203/cheok-yin-fung/perl/ch-2.pl
new file mode 100644
index 0000000000..5f20d3ace9
--- /dev/null
+++ b/challenge-203/cheok-yin-fung/perl/ch-2.pl
@@ -0,0 +1,49 @@
+# The Weekly Challenge 203
+# Task 2 Copy Directory
+# Usage: perl ch-2.pl $source $target
+use v5.30.0;
+use warnings;
+
+my $source = $ARGV[0];
+my $target = $ARGV[1];
+
+die "$source is not a directory" unless -d $source;
+die "$target is not a directory" unless -d $target;
+
+# dir_walk taken from "Higher Order Perl" by Mark Jason Dominus
+
+sub dir_walk {
+ my ($top, $code, $dirname) = @_;
+ my $DIR;
+
+ $code->($top, $dirname);
+
+ if (-d $top) {
+ my $file;
+ unless (opendir $DIR, $top) {
+ warn "Couldn't open directory $top: $!; skipping.\n";
+ return;
+ }
+ while ($file = readdir $DIR) {
+ next if $file eq "." || $file eq "..";
+ dir_walk("$top/$file", $code, $file);
+ }
+ }
+}
+
+sub copy_dir {
+ if ($_[1]) {
+ if (-d $_[0]) {
+ my $dirname = $_[1];
+ my $reldir = substr($_[0], length($source));
+ my $relpdir = reverse substr(
+ (reverse $reldir), index(
+ (reverse $reldir), "/"
+ )
+ );
+ `cd $target$relpdir && mkdir $dirname`;
+ }
+ }
+}
+
+dir_walk($source, \&copy_dir);