john-jones
john-jones

Reputation: 7780

Perl get file by regular expression

At a specific folder in the system there is a file. I know that its name is a number, and I have that number in a variable.

What i don't know is what extension this file has.

How do i scoop up this file?

Upvotes: 2

Views: 134

Answers (2)

Mark Reed
Mark Reed

Reputation: 95375

(my $filename) = glob "$specific_folder_in_the_system/$that_number.*";

EDIT: As Ikegami notes below, this is sensitive to the particular pathname of the directory. It will fail if that directory name contains spaces or other special characters. You can mitigate that by wrapping the non-wildcard portion of the string in embedded quotation marks:

(my $filename) = glob "'$specific_folder_in_the_system/$that_number.'*";

But that will still fail for e.g. $specific_folder_in_the_system = "/Users/O'Neal, Patrick";.

If you don't mind changing your current working directory, you can chdir($specific_folder_in_the_system) or die first and then use just glob("$that_number.*"), which should be safe as long as $that_number is really a number.

You could also use a combination of opendirand grep in lieu of glob:

opendir(my $dir, $specific_folder_in_the_system) or die;
(my $filename) = grep /^$that_number\./ readdir $dir;

Upvotes: 3

Zaid
Zaid

Reputation: 37156

my ( $file ) = glob "$num.*" ;

Upvotes: 2

Related Questions