Here is a quick solution that took me less time to write again than it would have taken to find where I wrote this before:
#!/usr/bin/perl
use strict;
use warnings;
use File::Spec; # Note that test data is Unix-format!
warn "Test data is in Unix format; may not work on $^O"
unless File::Spec->isa('File::Spec::Unix');
my @Files = map {chomp; $_} (<DATA>);
# find common prefix directories for a list of files; assuming that al
+l
# files are on the same volume, if the system has volumes
sub common_prefix (@) {
my @dirs = map {[File::Spec->splitdir((File::Spec->splitpath($_))[1]
+)]} @_;
my @prefix = @{shift @dirs};
foreach my $dir (@dirs) {
for (my $i = 0; $i < @$dir && $i < @prefix; $i++)
{ splice @prefix, $i unless $dir->[$i] eq $prefix[$i] }
}
return @prefix
}
print "Sample files:\n";
print ' ',$_,"\n" for @Files;
print "Common prefix:\n";
print ' ',File::Spec->catdir(common_prefix @Files),"\n";
__DATA__
/foo/bar/bax
/foo/bar/baz
/foo/baz/quux
Sample output:
Sample files:
/foo/bar/bax
/foo/bar/baz
/foo/baz/quux
Common prefix:
/foo
|