Perl fileparse Path Name

580 Views Asked by At

Here is my situation:

use strict;
use Cwd;
use Getopt::Long;
Getopt::Long::Configure('pass_through');
use File::Spec;
use File::Basename;

1) -out=/some/place/some_filename.txt
2) -out=/some/place/
3) -out=some_filename.txt

Any user can give any '-out=' as exampled above. I am interested in the pathname because I have to check if the directory is writable to create/overwrite a log file, and exit with a warning if the directory is not writable.

If -out= is option 1, then fileparse will give me '/some/place' and I can -w on that.

If -out= is option 2, then I can just -d and -w, then attach a default filename. Something like '/some/place/default_filename.txt'

If -out= is option 3, I have to attach 'my $cwd' to the filename. Something like '/current/working/dir/some_filename.txt'

The requested file may or may not pre-exist. The filename may be .log or .txt or .dat or no extension at all, depending on the user's whim, and I have to create/overwrite that file as needed.

So my question for the more experienced Perl tacticians here, since -out= will be uncertain from user to user, what is the best method to extract the pathname? I can do 'if (-d $out)', but what if the user just gave a filename? I may get lucky and the user may give the full path/filename, or just the directory path. Or the user may be satisfied with having his data in current working directory and will give only a filename. I inserted a filename into fileparse and got: "$path=./"

Roderick

1

There are 1 best solutions below

11
mvp On

You can simply check if your parameter is a directory (-d $out) and add default file name to it in that case. Then all you need to check if resultant file is writable and bail out if it isn't:

$out .= "/default_filename.txt" if -d $out;
die "File $out is not writable!" unless -w $out;
# everything ok, create file at $out:
open FILE, ">", $out or die "Cannot open $out for writing!";
# ...