in reply to Regular Expression Help
Both are the following portable and reliable. There difference is what happens when the trailing slash is ommited.
1) Anything after the last slash is considered a dir name:
my ($vol, $dirs) = File::Spec->splitpath($path, 1); $dirs = File::Spec->canonpath($dirs); my @dirs = File::Spec->splitdir($dirs); pop(@dirs); $dirs = File::Spec->catdir(@dirs); $path = File::Spec->catpath($vol, $dirs, '');
Test:
use strict; use warnings; use File::Spec (); foreach ( '/rootdir/sub1/sub2/sub3/sub4/', '/rootdir/sub1/sub2/sub3/sub4', '/rootdir/', '/rootdir', '/', 'C:\\', 'reldir/sub1/', 'reldir/sub1', 'reldir/', 'reldir', ) { my $path = $_; print("$path\n"); my ($vol, $dirs) = File::Spec->splitpath($path, 1); $dirs = File::Spec->canonpath($dirs); my @dirs = File::Spec->splitdir($dirs); pop(@dirs); $dirs = File::Spec->catdir(@dirs); $path = File::Spec->catpath($vol, $dirs, ''); print(" -> $path\n"); }
outputs:
/rootdir/sub1/sub2/sub3/sub4/ -> \rootdir\sub1\sub2\sub3 /rootdir/sub1/sub2/sub3/sub4 -> \rootdir\sub1\sub2\sub3 /rootdir/ -> \ /rootdir -> \ / -> \ C:\ -> C:\ reldir/sub1/ -> reldir reldir/sub1 -> reldir reldir/ -> reldir ->
2) Anything after the last slash is considered a file name:
my ($vol, $dirs) = File::Spec->splitpath($path, 0); $dirs = File::Spec->canonpath($dirs); my @dirs = File::Spec->splitdir($dirs); pop(@dirs); $dirs = File::Spec->catdir(@dirs); $path = File::Spec->catpath($vol, $dirs, '');
Test:
use strict; use warnings; use File::Spec (); foreach ( '/rootdir/sub1/sub2/sub3/sub4/', '/rootdir/sub1/sub2/sub3/file', '/rootdir/', '/rootfile', '/', 'C:\\', 'reldir/sub1/', 'reldir/file', 'reldir/', 'relfile', ) { my $path = $_; print("$path\n"); my ($vol, $dirs) = File::Spec->splitpath($path, 0); $dirs = File::Spec->canonpath($dirs); my @dirs = File::Spec->splitdir($dirs); pop(@dirs); $dirs = File::Spec->catdir(@dirs); $path = File::Spec->catpath($vol, $dirs, ''); print(" -> $path\n"); }
outputs:
/rootdir/sub1/sub2/sub3/sub4/ -> \rootdir\sub1\sub2\sub3 /rootdir/sub1/sub2/sub3/file -> \rootdir\sub1\sub2 /rootdir/ -> \ /rootfile -> \ / -> \ C:\ -> C:\ reldir/sub1/ -> reldir reldir/file -> reldir/ -> relfile ->
Note: The only difference is the second argument to splitpath.
|
|---|