views:

103

answers:

1

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.

+13  A: 

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"
}
meagar
Just to be complete, you can do `foreach (glob("*.file")) { something }` as well...
drewk
But I am unable to put regexp in there. Can I use regular expressions ?
alertjean
@alertjean No, you'll have to open the directory and manually scan file names using a regular expression. `glob` only supports the traditional [shell wild cards](http://www.tuxfiles.org/linuxhelp/wildcards.html).
meagar
@meager Got you ! Thanks !
alertjean
@alertjean You should work on your accept rate. When you get a good answer to one of your questions, you should mark it as accepted to "close" the question.
meagar