Thursday, June 5, 2008

Perl: Make multilevel directories

I didn't know before that it is possible to create multi-leveled directories using Perl easily with a single command. I mean, if you need to create all the folders of the path "C:\Folder1\Folder2\Folder3" if the are not exist.

What I did before, checked each folder, and if not exist, then create, and goes to next folder. My task was too much manual, and there was always a chance of error. Here is what I got recently. I just used the 'mkpath()' function from 'File::Path' module. It takes the file path as parameter, and create all while traverse. This command works for both Linux and Windows.
use strict;
use File::Path;

Before knowing this, I used to use something like below code. But below code is working only on Windows, if you need it to work on Linux, you need to convert all the back slashes(\) into forward slashes(\).
use strict;
use File::Path;
my $path = "C:\\Folder1\\Folder2\\Folder3";

## Seperate the foldernames into an array
my @folders = split(/\\/, $path);

$path = "";
foreach my $folder(@folders){
## Tracking the absolute path
$path = $path . $folder . "\\";
## If folder doesn't exist, then create this
if(! -e $path){
## Create the folder.

To read more about Perl programming topics, you can take a look at, Or you can search my blog for other programming languages.

No comments:

Get function name programaticaly - Python

This little piece of code will help you to get the function name programatically. This is very helpful when you are implementing the debug...