Sunday, February 8, 2015

Perl Script: Reading the list of files from Directory

There are couple of ways to get the list of files from withing directory.

#1 - Using the built-in Perl glob function
#2 - Using opendir, readdir and closedir

Below Perl script demonstrate the usage of above methods to get the list of files, feel free to copy and use this code.


Source: read_dir.pl
#!/usr/bin/perl

# Method #1 - using the built-in Perl glob function
@filelist = <*>;
foreach $filename (@filelist) {
  print $filename;


# Method #2 - Using opendir, readdir and closedir

$dir = "/home/poison";
opendir(DIR, $dir) || die "Problem reading the dir. \n";

# Read the entire file names into a array
#@filelist = readdir(DIR);

while ($filename = readdir(DIR)) {
  print $filename , "\n";
}
closedir(DIR);

Read more: http://linuxpoison.blogspot.kr/2013/01/perl-script-reading-list-of-files-from.html#ixzz3R9E1JrWt

0 comments: