Jean
Jean

Reputation: 22695

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.

Upvotes: 16

Views: 33329

Answers (3)

Matthew Lock
Matthew Lock

Reputation: 13486

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

Upvotes: 1

Jim Black
Jim Black

Reputation: 1482

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.

Upvotes: 0

user229044
user229044

Reputation: 239311

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"
}

Upvotes: 36

Related Questions