in reply to Path parsing from full to relative
I have found that fileparse helps me out in most situations. And since you are on Windows I recommend more checks. The following code checks if the path has a filename and checks the file suffix is correct. I've ran into trouble myself many times by not doing these simple things. The split instruction is added to get the dirname as you want it (though without the leading \)
use strict ; use warnings ; use File::Basename qw( fileparse ) ; my $fullpath = q{C:\somedirectory\anotherDirectory\WorkingDirectory\Lo +gs\myLogs.txt} ; my ( $filename, $dirname, $suffix ) = fileparse $fullpath, qr/\.[^.]*/ + ; if ( $filename ne "" && $suffix eq ".txt" ) { ( undef, $dirname ) = split( /(?=WorkingDirectory)/, $dirname ) ; print "filename = $filename\n" ; print "dirname = $dirname\n" ; print "suffix = $suffix\n" ; } else { die "Wrong path!\n" ; } print "shortpath = $dirname$filename$suffix\n" ; __END__ filename = myLogs dirname = WorkingDirectory\Logs\ suffix = .txt shortpath = WorkingDirectory\Logs\myLogs.txt
edit: Btw, if the split fails, dirname becomes undefined, so you can build a simple check for that as well.
|
|---|