0

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?

brian d foy
  • 129,424
  • 31
  • 207
  • 592
fixxxer
  • 15,568
  • 15
  • 58
  • 76
  • 5
    while its entirely your choice, i still would advice against using system calls like that unnecessarily since Perl has its in built ways to do that. you make your code not portable. – ghostdog74 Jan 08 '10 at 06:46

4 Answers4

9

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)

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
2

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`;
nobody
  • 19,814
  • 17
  • 56
  • 77
  • 3
    To clarify, `system` in the question's code starts a child process, namely `cd`, which __does__ change __its own__ working directory. Then the child process ends; but environmental changes such as working directory and environment variables have no effect on the parent process, i.e. the Perl script. – daxim Jan 08 '10 at 09:45
2

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

sud03r
  • 19,109
  • 16
  • 77
  • 96
0

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} <*>"
Anonymous
  • 49,213
  • 1
  • 25
  • 19