[Webinar] Streamline your web hosting managementRegister Today

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

display file names in dirs

i have this code that displays the name of all directories below a certain directory but id also like it to print the names of all files with the .txt extension that are below the directory ($dir)

$dir = "/data/local/apache/htdocs/uploads";

opendir DIR,$dir or die "can't open $dir $!";

while( $file=readdir DIR ){
print "file is $file<br>";
print "dirfile is $dir/$file<br>";
next unless -T "$dir/$file";
open FILE,"<$dir/$file" or warn "can't open <$dir/$file $!";
local $/=undef;



1 Solution
sub scan_dirs($)
      #Make scope relative to sub instance
      my $dir=$_[0];

      #my $nivel = $_[1];

      my (@dirs,@files,@results,$filename,$newdir,$list);

      #Open dir handle

      #Aplicar filtro con grep al readdir
      @dirs=grep {!(/^\./) && -d "$dir/$_"} readdir(dir);      

      #Order alpabeticamente
      @dirs = sort @dirs;


      #Get Files

            @files=grep {!(/^\./) && !(-d "$dir/$_") && (-T "$dir/$_")} readdir(dir);

      #Ordenar Archivos
      @files = sort @files;
      closedir (dir);
      #Foreach Dir (Only if you want recursive)
      for $list(0..$#dirs)
            #Armar dir para proximo paso recursivo del sub

            print "Dir: $newdir\n";
                  #Foreach Dir (Only if you want recursive)

      foreach $file (@files)
            print "File: $file\n";
}#Fin del Sub Scan_Files

This will print out the dirs and files from a starting point and if you uncomment the line:


It will also recurse.

Call the sub by passing it a starting dir like this:


Featured Post

Take Control of Web Hosting For Your Clients

As a web developer or IT admin, successfully managing multiple client accounts can be challenging. In this webinar we will look at the tools provided by Media Temple and Plesk to make managing your clients’ hosting easier.

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