Re: recursive functions

From: thundergnat (thundergnat_at_hotmail.com)
Date: 08/04/04


Date: Wed, 04 Aug 2004 15:25:46 -0400

Abhinav wrote:

> 4. Directory search of a file system

Heres something I had done at one point.
This could be MUCH more efficiently done with File::Find
but I wrote this to noodle around with recursion.

Print a manifest of a directory tree with file sizes to a file
$dir.mft.

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

my $dir = $ARGV[0];
die "You must specify a starting directory" unless $dir;
$dir =~ m/[\\\/](\w+)[\\\/]?$/;
die "Bad directory name: $dir" unless $1;
my $name = $1.".mft";
my $cwd = getcwd;
my ($indent,$index,@mfst);
my $space = '';

mft($dir);

chdir $cwd;
open my $MFST, ">$name" or die "Could not open file $!";
print $MFST "Manifest for $dir.\n\n";
print $MFST @mfst;

sub mft{
     my $dir = shift;
     $indent += 2;
     chdir $dir;
     my @list = glob("*");
     foreach my $file(@list) {
         if (-d $file){
         push @mfst, (' ' x $indent).$file."\n";
             mft($file);
         }else{
             push @mfst, (' ' x $indent).$space.$file.' '.
             (((-s $file)>1024) ?
             (sprintf "%.1f", (-s $file)/1024)."K\n" :
             (sprintf "%d", (-s $file))."B\n");
         }
     }
     $indent -= 2;
     chdir '..';
}