Image of the glider from the Game of Life by John Conway
Skip to content

Simple Recursion in Perl

I'm going to embarrass myself today, and post some hack-ish Perl code using recursion. Actually, because the code is only 35 lines, I think it turned out actually fairly well, but as I am a Perl n00b, I am sure that the experts out there will disagree with the quality of the code.

First and foremost, I have a global variable used as a counter. I know that this is a BIG NO-NO, but, because the code is only 35 lines in length, I'm not too worried. I do recognize, though, that passing the counter by reference through the recursive function PrintFiles() would probably be the better way to handle that, but then, that's just making things a bit more difficult than I care at this point.

What does the program do? It should be fairly obvious: it runs through a root directory structure, looking for OGG Vorbis files, counting them, and printing the results to another text file for inventory. Basic, gets the job done, and without a lot of fanfare. The code should be self-evident, but I'm anal about commenting code, so redundant comments are placed throughout. The program was just an exercise for me to:

  1. Increase my ability to do simple recursion.
  2. Learn recursion using Perl.
  3. Create an inventory of my music.

Anyway, here's the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!/usr/bin/perl -w

open(OUT, ">oggfiles.txt"); # Create the file to read to
$counter = 0;   # Global variable (no-no)!! :)

sub PrintFiles  # Recursive function for printing dir contents
{
    my ($indent) = @_;  # Keep track of indentation
    opendir(MD, "./");  # Start looking through local directory
   
    foreach my $file (sort readdir MD)  # Start a loop going through each dir sorted
    {
        unless($file =~ m/^\./ || $file =~ m/^ogg/) # Prevent an infinite loop, don't worry about hidden (.*), oggdir.pl and oggfiles.txt files
        {
            $counter++ if $file =~ m/\.ogg$/;   # Keep a counter for every ogg file
           
            print OUT $indent . $file . "\n";   # Print dir contents to a file
           
            if (-d $file)   # If a directory
            {
                chdir $file;    # Change to the directory
                PrintFiles("$indent  ");    # Call the recursive function again, incrementing the ident
                chdir "../";    # Change back
            }
        }
    }
   
    closedir(MD);   # Close the dir
}

PrintFiles("");     # First call of the recursive function, with no spaces for indentation

print OUT "\nCurrent number of music files: " . $counter . "\n\n";

close(OUT); # Close file written to

{ 4 } Comments