How can I test if a filename matching a pattern exists in Perl?

Can I do something like this in Perl? Meaning pattern match on a file name and check whether it exists.

    if(-e "*.file")
    {
      #Do something
    }

I know the longer solution of asking system to list the files present; read it as a file and then infer whether file exists or not.

Answers


You can use glob to return an array of all files matching the pattern:

@files = glob("*.file");

foreach (@files) {
    # do something
}

If you simply want to know whether a file matching the pattern exists, you can skip the assignment:

if (glob("*.file")) {
    # At least one file matches "*.file"
}

On *nix systems, I've used the following with good results.

sub filesExist { return scalar ( my @x = `ls -1a 2> /dev/null "$_[0]"` ) }

It replies with the number of matches found, or 0 if none. Making it easily used in 'if' conditionals like:

if( !filesExist( "/foo/var/not*there.log" ) &&
    !filesExist( "/foo/var/*/*.log" ) &&
    !filesExist( "/foo/?ar/notthereeither.log" ) )
{
    print "No matches!\n";
} else {
    print "Matches found!\n";
}

Exactly what patterns you could use would be determined by what your shell supports. But most shells support the use of '*' and '?' - and they mean the same thing everywhere I've seen. Of course, if you removed the call to the 'scalar' function, it would return the matches - useful for finding those variable file names.


On Windows I had to use File::Glob::Windows as the Windows path separating backslashes don't seem to work perl's glob.


Need Your Help

Android: Kotlin with Butterknife

android kotlin butterknife

I'm trying to use Kotlin with Butterknife for my Android Application.

When using an Android Library Project how do you reference xml resources properly?

android xml android-library

I have an Android Library Project that contains several styles/themes defined in its styles.xml file.