[Israel.pm] How to Best Process the Directory Components of a Path
shlomif at iglu.org.il
Thu Apr 3 10:44:27 PDT 2008
I'm trying to process the directory components of a path (as an array) so
1. It will be portable. (Work on Unix, Windows, VMS, etc.)
2. It will keep the rest of the path components (if any) identical.
3. It will work on both relative and absolute paths.
If the processing is to keep only the directories after "long-dir" then:
UNIX : /hello/there/long-dir/another/myfile.txt ==> another/myfile.txt
DOS : C:\Hello\There\Long-Dir\Another\myfile.txt ==> another\myfile.txt
UNIX: ./hi/long-dir/another/myfile.txt ==> another/myfile.txt
DOS: .\hi\long-dir\another\myfile.txt ==> another\myfile.txt
To do this I turned to File::Spec and File::Basename and wrote the following
code which seems insanely complicated. I marked the place where I do the
actual processing using a callback:
my ($self, $fn, $callback) = @_;
my $basename = basename($fn);
my $dirpath = dirname($fn);
my ($volume, $directories, $filename) = File::Spec->splitpath($dirpath,
# The actual manipulation.
my $dirs = $callback->([File::Spec->splitdir($directories)]);
my $final_dir =
$volume, File::Spec->catdir(@$dirs), $filename
if ($final_dir eq "")
And so far I checked it works only on UNIXes (Linux in my case) and on
So my questions are:
1. Is there a simpler way to do it?
2. Does Path::Class or File::Fu or a different abstraction provide an easier
way to do it?
3. Is it still buggy?
I should note that this hairiness is not limited to Perl. Common Lisp has a
built-in portable path-manipulation abstraction that's also relatively
Shlomi Fish shlomif at iglu.org.il
I'm not an actor - I just play one on T.V.
More information about the Perl