Traversing Through Directories

150 Views Asked by At

I am trying to traverse through directories to change certain file extensions in those directories.

I made it to where I can go through a directory that is given through command-line, but I cannot make it traverse through that directories' subdirectories.

For example: If I want to change the file extensions in the directory Test then if Test has a subdirectory I want to be able to go through that directory and change the file extensions of those files too.

I came up with this. This works for one directory. It correctly changes the file extensions of the files in one specific directory.

#!/usr/local/bin/perl

use strict;
use warnings;


my @argv;
my $dir = $ARGV[0];

my @files = glob "${dir}/*pl";
foreach (@files) {
    next if -d;
    (my $txt = $_) =~ s/pl$/txt/;

    rename($_, $txt);
}

I then heard of File::Find::Rule, so I tried to use that to traverse through the directories.

I came up with this:

   #!/usr/local/bin/perl

use strict;
use warnings;
use File::Find;
use File::Find::Rule;

my @argv;
my $dir = $ARGV[0];
my @subdirs = File::find::Rule->directory->in( $dir );

sub fileRecurs{
        my @files = glob "${dir}/*pl";
        foreach (@files) {
                next if -d;
                (my $txt = $_) =~ s/pl$/txt/;
                rename($_, $txt);
                }
           }

This does not work/ will not work because I am not familiar enough with File::Find::Rule

Is there a better way to traverse through the directories to change the file extensions?

1

There are 1 best solutions below

0
On BEST ANSWER
#!/usr/local/bin/perl

use strict;
use warnings;
use File::Find;


my @argv;
my $dir = $ARGV[0];

find(\&dirRecurs, $dir);

sub dirRecurs{


        if (-f)
        {
                (my $txt = $_) =~ s/pl$/txt/;
                rename($_, $txt);
        }

}

I figured it out with the help of the tutorial @David sent me! Thank you!