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

Jean picture Jean · Oct 19, 2010 · Viewed 29.5k times · Source

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.

Answer

meagar picture meagar · Oct 19, 2010

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