Unable to complete a command from prompt line, using qx in Perl

155 Views Asked by At

I need my perl program to execute a DIR command in the windows command line. I use these lines:

$percorso1= C:\PerlEsercitazione\FileCompare1\VSS\Divina Cömmediä\ProgettoTest
my $cmd_string = "dir /ad /b ".$percorso1 ;
my @result = qx {$cmd_string};                              

obviously $percorso1 is the path to follow. The problem is that @result turns out to be empty. I typed the DIR command directly in the shell and it works, so the problem should be in the qx function. Where am I wrong?

anyway I tried using readdir ,opendir and closedir but using this code:

opendir ("Temp_VSS", $percorso1);
my @result = readdir ($percorso1);
closedir ("Temp_VSS");

and I get the error "bad symble for dirhandle"

2

There are 2 best solutions below

3
On

Not sure why does this fail (could be that dir is not really an executable but rather a shell command so you could try with cmd /c "dir /ad /b $percorso1"). But generally it's better to avoid external programs for something you have internal functions.

Here specifically File::Slurp::read_dir can do the same for you much easier and with internal error handling:

my @files = File::Slurp::read_dir($percorso1, err_mode => 'carp', keep_dot_dot => 0);
0
On

The $percorso1 declaration is missing the quotes. You will need to backslash the backslashes. The line should end with a semicolon. Also you will need use utf8; because your source code contains utf8 encoded characters.

For the second snippet look here: Perl: Bad Symbol for dirhandle