Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 449
Jean Avatar asked Oct 18 '10 22:10

Jean


People also ask

How to search for a pattern in Perl?

Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to host language and are not the same as in PHP, Python, etc.

How do I check if a file exists in Perl?

Perl has a set of useful file test operators that can be used to see whether a file exists or not. Among them is -e, which checks to see if a file exists.

What is glob Perl?

glob() function in Perl is used to print the files present in a directory passed to it as an argument. This function can print all or the specific files whose extension has been passed to it. Syntax: glob(Directory_name/File_type); Parameter: path of the directory of which files are to be printed.


1 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"
}
like image 143
meagar Avatar answered Sep 19 '22 08:09

meagar