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.
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.
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.
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.
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With