perlperl-moduleperlop

How to check if a file name contains directory info?


I would like to check if a file name has any directory information within it, preferably without using a system dependent hack like index($file_name,'/')!=-1. I know of the File::Spec module, but can't seem to find a way to use that module to make this determination. Perhaps another module would work better. Here are some examples of file names:

# This does not have directory info, so the test should fail (i.e., return false)
my $file_name1='abc.txt';

# These do have directory info, so the test should succeed (i.e., return true)
my $file_name2='dir/abc.txt';
my $file_name3='/home/me/abc.txt';
my $file_name4='~me/abc.txt';

Solution

  • splitdir will return a list. Evaluated in scalar context, it returns the number of items in the list. If there is more than 1 item in the list, then you know there is a directory separator.

    use warnings;
    use strict;
    use File::Spec qw();
    
    while (<DATA>) {
        chomp;
        if (File::Spec->splitdir($_) > 1) {
            print 'PASS';
        }
        else {
            print 'FAIL';
        }
        print ": $_\n";
    }
    
    __DATA__
    abc.txt
    dir/abc.txt
    /home/me/abc.txt
    ~me/abc.txt
    

    Prints:

    FAIL: abc.txt
    PASS: dir/abc.txt
    PASS: /home/me/abc.txt
    PASS: ~me/abc.txt