« Timing Is Everything | Main | A shorter filesystem recurser in Perl »

Recursivly print directories in Perl...with no modules

Just for fun I came up with some Perl to recursively print out a directories files and child directories. Why am I posting it? It's not that it's all that difficult or obscure, I just feel like it, and when I did a web search for code on this that doesn't use the File::Find Perl module, I was surprised as to how few results there were. So in the interest of reinventing the wheel a bit, here's what I came up with.

#!/usr/bin/perl use strict; use warnings;

printdir( $ARGV[0] );

sub printdir
     my $dir          = $_[0] ? $_[0] : '.';
     my $handle      = ();
     my @dirs      = ();
     my $i           = ();
     print "Directory: $dir\n";
     opendir( $handle, $dir );
     my @items = readdir( $handle );
     closedir( $handle );
     shift @items; #Get rid of .
     shift @items; #Get rid of ..
     @items = sort( @items );
     while ( $i = shift( @items ) )
          if ( -d "$dir/$i" )
               push( @dirs, $i );
          print "$dir/$i\n";
     printdir( "$dir/$i" ) while ( $i = shift( @dirs ) );

Comments (1)

Hey, thanks for this, is awesome. I created one but limited to 3 dirs, yours is just awesome. Thanks

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)


This page contains a single entry from the blog posted on August 26, 2006 10:49 AM.

The previous post in this blog was Timing Is Everything.

The next post in this blog is A shorter filesystem recurser in Perl.

Many more can be found on the main index page or by looking through the archives.