Find common directory path: Difference between revisions

→‎{{header|Perl}}: greatly simplify and clean up the existing solution, while staying true to its spirit
(Added zkl)
(→‎{{header|Perl}}: greatly simplify and clean up the existing solution, while staying true to its spirit)
Line 1,107:
=={{header|Perl}}==
 
A solution that tallies up all potential prefixes from all given paths, and finds the longest one that occurred in all paths:
Assuming all paths begin at root.
 
<lang Perl>use List::Util qw(max reducefirst);
 
sub compath {
sub common_prefix {
my ($sep, @paths, %hash) = @_;
#my Tokenize($sep, and@paths) tally= subpaths@_;
my %prefixes;
}
foreach (@paths) {
mydo @tok{ =++$prefixes{$_} split} while s/$sep, substr([^$_,1);sep]*$//
}
++$hash{join $sep, @tok[0..$_]} for (0..$#tok); }
# Return max length subpath or null
return first { $prefixes{$_} == @paths } reverse sort keys %prefixes;
my $max = max values %hash;
}
return '' unless $max == @paths;
my @res = grep {$hash{$_} == $max} keys %hash;
return $sep . reduce { length $a > length $b ? $a : $b } @res;
}
 
# Test and display
Line 1,127 ⟶ 1,126:
/home/user1/tmp/covert/operator
/home/user1/tmp/coven/members);
print compathcommon_prefix('/', @paths), "\n";</lang>
 
{{out}}
Output:
<pre>/home/user1/tmp</pre>
 
Anonymous user