Complete Communications Engineering

Perl has built-in functions that can be used for this.  The functions are ‘opendir’, ‘readdir’ and ‘closedir’.  The ‘opendir’ function takes the path to a folder as input, opens the folder and returns a handle to it in a variable.  The handle can then be used in the ‘readdir’ function to get the folder’s contents as a list variable.  Once the list is obtained, the ‘closedir’ function can be used to close the folder.  The list variable can then be iterated over.  Perl supports a number of file test operators that can be used to decide how to handle each entry in the list.  The following example demonstrates how to iterate files in a folder tree:

treeiter.prl

#!/usr/bin/perl

 

sub process_file {

    my ($path) = @_;

    print “Processing file $path\n”;

}

 

sub process_folder {

    my ($folder) = @_;

 

    # Get a directory listing

    opendir (my $dir, $folder);

    my @files = readdir ($dir);

    closedir ($dir);

 

    # Decide how to handle each entry

    foreach my $file (@files) {

 

        # Ignore some specific entries

        next if ($file eq “.”);

        next if ($file eq “..”);

 

        # Handle folders recursively

        my $path = $folder/$file;

        if ( -d $path ) {

            process_folder($path);

            next;

        }

 

        # Handle files

        if ( -f $path) {

            process_file($path);

            next;

        }

    }

}

 

# Start in the current folder

process_folder(“.”);

This example defines two functions: ‘process_file’ and ‘process_folder’.  The function ‘process_file’ is called for each file in the directory tree and receives the full path to the file relative to the start folder.  The function ‘process_folder’ is called for each folder that is encountered.  It is called once to start the iterative process, and it is called recursively on every sub-folder that is found.  It will skip the entries “.” and “..” which are both considered directories but will cause problems if the function tries to process them.  The example uses the “-d” and “-f” test operators to handle directories and files differently.