Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 363
  • 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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

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