views:

212

answers:

4

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?

+9  A: 

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)

ghostdog74
A few lines of code would be really helpful.
fixxxer
So it is the documentation.
Leonardo Herrera
+2  A: 

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`;
Andrew Medico
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
+2  A: 

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

Neeraj
:DI used something similar.
fixxxer
A: 

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