Tutorial :How can I get a directory listing from DOS in Perl?


I need to get directory names from the path passed to the Perl script as run time argument. Here is the code I'm using:

$command ="cd $ARGV[0]";  system($command);    $command="dir /ad /b";  system($command);  @files=`$command`;  

But it still returns the directory names inside the directory from which I'm running this Perl script. In short, how do I get the directory names from a target directory whose path is passed to this Perl script?


This should also work
$command = "dir /ad /b $ARGV[0]" ;


judging from what you are trying to do in your question post

$dir = $ARGV[0];  chdir($dir);  while(<*>){   chomp;   # check for directory;   if ( -d $_ ) {      print "$_\n" ;   }  }  

on the command line

c:\test> perl myscript.pl c:\test  

There are other methods of doing a listing of directory. See these from documentation

  1. perldoc -f opendir, perldoc -f readdir

  2. perldoc perlopentut

  3. perldoc -f glob

  4. perldoc perlfunc (look at operators for testing files. -x, -d, -f etc)


Your problem is that running "cd" via "system" does not change the working directory of the perl process. To do so, use the "chdir" function:

chdir($ARGV[0]);    $command="dir /ad /b";  system($command);  @files=`$command`;  


use File::DosGlob (core since before perl v5.5) to avoid gotchas like skipping files matching /^\./.

perl -MFile::DosGlob=glob -lwe "chdir 'test_dir'; print for grep {-d} <*>"  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »