diff options
author | Guillermo Ramos | 2019-06-14 10:43:24 +0200 |
---|---|---|
committer | Guillermo Ramos | 2019-06-14 10:43:34 +0200 |
commit | 89aaa58e0df44a6a731411d6bf025e9cf1855a4c (patch) | |
tree | 2b14012b9f46655391a4ca3f0a6ca485635dfcbc /012 | |
parent | cdd1b6a4c2f7407f5393a0dc88f35a126be96213 (diff) | |
download | perlweekly-89aaa58e0df44a6a731411d6bf025e9cf1855a4c.tar.gz |
[012#2]
Diffstat (limited to '012')
-rwxr-xr-x | 012/ch2.pl | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/012/ch2.pl b/012/ch2.pl new file mode 100755 index 0000000..6c12861 --- /dev/null +++ b/012/ch2.pl @@ -0,0 +1,35 @@ +#!/usr/bin/env perl + +use strict; +use warnings; + +sub commonPath { + # Normalize paths (merge multiple "/"s into a single one) + map s|/+|/|g, @_; + + # This array stores the common path components so far + my @common = split m|/|, shift, -1; + + # Iterate over arguments (paths) and update @common accordingly + foreach my $path (@_) { + my @current = split m|/|, $path, -1; + + # Cut @common if longer than the current one + @common = @common[0 .. $#current] if $#current < $#common; + + # Cut @common to keep only the matching components + foreach my $i (0 .. $#common) { + if ($common[$i] ne $current[$i]) { + @common = @common[0 .. $i-1]; + last; + } + } + } + + # Corner case: @common == ('') means root + return @common == 1 && $common[0] eq '' + ? "/" + : join "/", @common; +} + +print commonPath(@ARGV), "\n"; |