Creating Directories

The first step in writing our HTML files is to make sure that all the directories our script is going to be writing to already exist. If they don’t, the script won’t be able to open files in them for writing. So, we’ll need to check for any of those directories that might be missing and create them if necessary.

In the script, that happens right after the (now-commented-out) debugging section:

# make sure all the directories we'll need exist

my @dirs = ($base_path, "$base_path/alpha", "$base_path/cats",
            "$base_path/listings");

We start by creating a @dirs array that contains a list of all the directories that we want to make sure exist already. As you can see, we’re including in that list the $base_path directory from the script’s configuration section, as well as subdirectories of that directory named alpha, cats, and listings.

Next, we need to add a directory under listings for each letter of the alphabet. We do this with the following block of code:

foreach my $letter ('a' .. 'z') {
    push @dirs, "$base_path/listings/$letter";
}

This uses a foreach loop, but the parentheses have something unusual inside them: Perl’s very cool range operator, which consists of two dots (..) with something on either side of them. The normal way the range operator is used is to return a list of numbers, as in 1 .. 10, which would return a list of the numbers 1 through 10. But it also can return a range of strings, which means the 'a' .. 'z' used in this example returns a list ...

Get Perl for Web Site Management now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.