hi i write this code in perl
i dont know why that not work...

sub Again
    {
        $dirtoget= $_[0];
        if(opendir(DH, $dirtoget))
        {
            @thefiles = readdir(DH); 
            closedir(DH);

            if(@thefiles)
            {
                foreach $f (@thefiles)
                {
                     next if ($f eq "." or $f eq "..");
                     print "$f\n";
                     if(-d "$dirtoget/$f")
                     {
                        Again("$_[0]/$f");
                     }
                }
            }
        }
        else
        {
            return;
        }       
    }

   $dirtoget = "c:/Exam";
    Again($dirtoget);

thankss...

Recommended Answers

All 2 Replies

Hello moshe12007,
To make your script work why not just use use strict and declare all your variable with my, as i have done below in case 1, and I believe your code should work. However, except for just checking out how recursion works on file directory using Perl, I think you might want to consider the case 2 code which is more effective and faster.

case 1:

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

sub Again {
my $dirtoget = $_[0];
if ( opendir( DH, $dirtoget ) ) {
    my @thefiles = readdir(DH);
    closedir(DH);
    if (@thefiles) {
        foreach my $f (@thefiles) {
            next if ( $f eq "." or $f eq ".." );
            print "$f\n";
            if ( -d "$dirtoget/$f" ) {
                Again("$_[0]/$f");
            }
        }
    }
}

#else { ## not needed
return;

#}## not needed
}
my $dirtoget = "c:/Exam";
Again($dirtoget);

case 2: A more effective way to do it.

#!/usr/bin/perl 
use warnings;
use strict;
use File::Find;
use Carp qw(croak);

croak "Please, specify your path: $!" unless defined $ARGV[0];

my $filepath = $ARGV[0];    ## get the path from CLI i.e script_name.pl "c:\Exam"
find( \&again, $filepath ); ## Instead of writing the recursive yourself use this

sub again {                 ## your again subroutine
if ( $_ ne '.' ) {
    if (-d) {           ## test directory
        print "Directory ( ", $_, " ) contains file(s): ", $/;
    }
    else { print "\t", $_, $/; }
}
print $filepath, $/ if $_ eq '.';
}

I hope this proves useful to you.
cheers.

thanks.... that very help me... i sounds about that module but i dont know why i think that recursing better then this module..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.