• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 365
  • Last Modified:

How to find the list of certain files in a given directory in Perl?

How can I find the list of certain files in a given directory and push them into an array?

Sudo Code:
findFiles($dir, $givenFileType){
 
 for my $file (each file in the dirctory){
   $fileType = get the file type of the $file
   if $fileType eq $givenFileType{
      push (@fileList, $file)
   }
 }
}

Open in new window

0
Tolgar
Asked:
Tolgar
1 Solution
 
TolgarAuthor Commented:
If there is another way of doing it more efficiently, I'd accept it as well.

I use Perl v5.8.8

Thanks,
0
 
TintinCommented:
Simply do

push @fileList, <*.$givenFileType>;

Open in new window

0
 
amarpal0102Commented:
Here is the whole tutorial about dir and files

http://perlmeme.org/faqs/file_io/directory_listing.html
0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

 
TintinCommented:
Any reason you didn't like my efficient solution instead of a link to a documentation page?
0
 
TolgarAuthor Commented:
Because it does not satisfy my requirements. It was a link but the link had exactly what I asked for.

When I looked at your solution, I cannot see anything that's related to a directory. I cannot specify a directory and also it does not search all the files in the subdirectories.

Sorry,

Thanks,
0
 
TintinCommented:
You didn't mention anything about subdirectories in your requirements or pseudo code.

push @fileList, <$dir/*.$givenFileType>;

Open in new window


is a shorthand way of writing

foreach my $file (<$dir*./$givenFileType>) {
   push @fileList, $file;
}

Open in new window

0
 
ozoCommented:
push @fileList, <$dir/*.$givenFileType>;

Open in new window

is a shorthand way of writing
 for my $file ( <$dir/*> ){
   $fileType = (fileparse $file,qr/(?<=\.)\Q$givenfiletype\E/)[-1];
   if( $fileType eq $givenFileType ){
      push (@fileList, $file)
   }
 }

Open in new window

0
 
TolgarAuthor Commented:
Thanks for the detailed info.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Tackle projects and never again get stuck behind a technical roadblock.
Join Now