Thursday, August 21, 2008

Example for use of grep(), map() and readdir()

You should have used readdir() to read contents of a directory. For that you have to open a directory as in:

opendir(DIR, "$directory_path");

After which readdir(DIR) returns an entry or all directory entries depending on the context.

my $file = readdir(DIR); # returns only single entry
my @files = readdir(DIR); # returns all the directory entries

But the values returned will not have the absolute path. For this reason, I use map to prefix the path for each entry ...

my @files = map { "$directory_path/$_" } readdir(DIR);

Now using the code given above all directory entries will have absolute paths.

If you want to grep for a pattern & collect only those entries that match a pattern use grep {}, like this:

my @files = grep { /pattern/ } map { "$directory_path/$_" } readdir(DIR);

In the above example, using grep {} before or after map {} makes a difference.

0 comments: