Print A List Of All Files Including Directories

under Programming Perl Gist

 

Writes list of all files and subdirectories for a given path to standard output. Not really useful on it’s own, but recurse subroutine is a good base to recursive file processing.

#!/usr/bin/perl
# Copyright (C) 2003 Andrew Loree
# $Id: filelist.pl,v 1.1.1.1 2003/10/05 21:51:29 andy Exp $
############################################################################
#
# filelist - Print a list of all files including directories
#
############################################################################
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2
#  of the License, or (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
#############################################################################
# Version History:
#   1.0  - Initial Release
#############################################################################


use strict;
use File::Basename qw(basename);
use FileHandle;

my $program = basename($0);
my $version = "1.0";
my $argc = @ARGV;


    if ($argc != 1) {
        usage();
    }

    # check for valid dir
    if (-d $ARGV[0]) {
        &recurse($ARGV[0]);
    }
    else{
        print STDERR "\nInvalid directory \'$ARGV[0]\'\n";
        usage();
    }


sub recurse{
my(@files);
my($path) = $_[0];
my($depth) = $_[1];
my($name);
my($sep) = "\\";

    # Add trailing slash
    if (!($path =~ /\\$/)){
        $path = $path . $sep;
    }

    print $path . "\n";
    opendir(DIR,$path) || die "can't opendir $path: $!";
    @files = readdir(DIR);
    closedir DIR;
    
    for $name (@files){
        if (-f $path . $name){
            print $path . $name . "\n";
        }
        if ((-d $path . $name) &&( ($name ne "..") && ($name ne ".") )){
            &recurse($path . $name . $sep,$depth+1);
        }
    }
}



sub usage {

    print STDERR <<END_OF_USAGE;

NAME
     $program -- Prints a list of files including directories

USAGE
     $program directory

DESCRIPTION
     directory    Directory to list files in

VERSION
    $version

END_OF_USAGE

    exit 0;
}