Krishna P Krishna P - 1 year ago 74
Perl Question

How to check if an argument has both filename and a path or just the filename

User input can be just a filename / filename with a path of where the file
exists. These are the only 2 options to users.

use File::Basename qw(dirname basename);

my $input = <STDIN>;
my $file = basename($input);
my $path = dirname($input);

Whenever user gives just the file name, i am getting path as .(DOT - current directory). The file doesn't exist in that path. For me if the user doesn't provide the path it means i pick it from a specific directory.

I am currently using a crude logic of checking the length of $path to see if a path is given or not.

Is there any other way which i can use which tells if path is mentioned or not. Any inputs are really helpful.

Answer Source

You could just check if there's a / in the $input.

use File::Basename qw(dirname basename);

my $input = <STDIN>;
my ($file, $path);

if ($input =~ m{/}) {
    $file = basename($input);
    $path = dirname($input);
} else {
    $path = '/foo/bar/';
    $file = $input;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download